没有用于初始化C++中的变量模板的匹配构造函数

No matching constructor for initialization of variadic template in C++

本文关键字:构造函数 变量 用于 初始化 C++      更新时间:2023-10-16

试图学习Variadic templates,但不知道为什么它不会编译,错误是:CCD_ 2。

在我们讨论的时候,我想提出第二个问题,澄清我在代码中的意见。

template <typename ...Args>     // this is just how Variadic template are defined
class test {
public:
int arr[sizeof...(Args)];       // this is packing or unpacking? why are 
// dots outside of bracket?
test(Args... arg)               // this is called packing?
: arr{arg...}{}   // this is called un-packing?
};
int main(){
test<> t(1,2,3);
return 0;
}

编辑:似乎我需要做test <int, int, int>,但为什么我必须这样做,因为另一个例子是这样工作的:

template <typename ...Args> 
int func(Args... arg)
{
int a[] = {arg...};
return sizeof...(arg);
}
int main(void)
{
std::cout << func(1,2,3,4,5,6) << std::endl;
return 0;
}

func不需要<int, int ,int..部分。

您的第一个示例不起作用,因为您需要指定以下类型

int main() {
test<int, int, int> t(1,2,3);
return 0;
}

如果你能使用C++17,你可以利用类模板的参数推导,并有这样的东西:

int main() {
test t(1,2,3);
return 0;
}

但在C++17之前,类模板参数推导不存在。但是,存在函数模板参数推导。这就是为什么您的第二个示例可以在不显式指定模板类型的情况下工作。

相关文章: