尝试学习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,则可以利用类模板参数推导的优势,例如:
int main() {
test t(1,2,3);
return 0;
}
但是在C ++ 17之前,不存在类模板参数推导 。但是,存在函数模板参数推导。这就是为什么第二个示例无需显式指定模板类型即可工作的原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句