c++ - 为什么 deduced_class_template_compound_type 会出现 clangd 错误?
问题描述
以下代码编译失败
template<typename T>
struct A {
A(T) {}
};
int main() {
int x = 3;
A(x); // compile failure here
}
原因似乎在这里和这里都有解释:A(x);
被解释为A x;
,一个相互矛盾的声明x
。
这也解释了其中一条 clang 消息:
Candidate function template not viable: requires 1 argument, but 0 were provided
prova.cpp:8:7: error: no viable constructor or deduction guide for deduction of template arguments of 'A'
另一方面,clangd 也说:
Cannot use parentheses when declaring variable with deduced class template specialization type [deduced_class_template_compound_type]
这个错误实际上指的是什么?我只能用一种方式解释它:没有括号,我可以提供所需的参数,例如A x{3};
,但是使用括号我不能声明一个变量,也不能将参数传递给它的构造函数,例如A(x)(3);
不起作用,也不行A(x){3};
。
为什么这么问?
在C++ 中的函数式编程的第 11 章中,作者在探索/解释 DSL 时,使用了模板辅助函数来构造模板类的对象。另一方面,假定代码至少是用编译的-std=c++17
(实际上,它利用了其他 C++17 特定的特性,如折叠表达式),所以原则上,如果构造函数,类可以推断模板类型提供了采用该模板类型的参数,示例就是这种情况。但是,删除辅助函数并将类重命名为(已删除的)辅助函数的名称,会使新代码无法在调用站点编译,其中使用语法构造对象className(objectOfOtherClass)
。
解决方案
推荐阅读
- php - 如何解决尝试访问 null 类型值的数组偏移量错误?
- python - 客户端推送内联键盘按钮后如何调用函数?
- json - Go:读取 JSON 文件与读取 JSON 字符串
- maven - Maven 在 Jenkins 上构建 - 上游版本范围解析为在并发作业中构建的版本
- string - Vue:过去的事件目标值在第一次粘贴时给了我一个空字符串
- r - 使用 menuSubItem 组织输入
- mongodb - 更新 postSQL 和 mongodb 之间的查询性能
- ruby-on-rails - 覆盖thoughtbot/clearance user.rb 不工作
- kubernetes - GKE 上的 Istio - Admission webhook 无法注入 sidecar-porxy
- c++ - 在 C++ 中生成对的排序向量的有效方法