gpt4 book ai didi

c++ - 在C++中没有匹配的构造函数来初始化可变参数模板

转载 作者:行者123 更新时间:2023-12-02 10:05:28 25 4
gpt4 key购买 nike

尝试学习Variadic templates却不知道为什么无法编译,错误是:no matching constructor for initialization of 'test<>'

在讨论过程中,我想通过在代码中阐明我的意见来提出第二个问题。

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,则可以利用 class template argument deduction并获得以下类似信息:

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

但是在C++ 17之前,类模板参数推导 不存在。但是,存在函数模板参数推导。这就是为什么第二个示例无需显式指定模板类型即可工作的原因。

关于c++ - 在C++中没有匹配的构造函数来初始化可变参数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60397447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com