首页 > 解决方案 > 为什么 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)

标签: c++compiler-errorsc++17most-vexing-parse

解决方案


推荐阅读