我在编译这段代码时遇到问题。
我想要做的就是创建一个可变参数类模板,它可以为我提供传入的所有元素的总和(例如 1,2,3,4,5,6 应该为 21)无论它是 int
或 float
。我基本上可以用两个函数模板递归地完成它,我得到了正确的答案,但是当我在类里面实现它时,它没有给我答案。
template <typename T>
class Myclass
{
public:
T sum;
T func(T A,T... B)
{
sum+=A;
func(B...);
}
T func(T A)
{
sum+=A;
return sum;
}
};
int main()
{
Myclass<int> myclass;
cout<<myclass.func(12,11,11,23);
return 0;
}
最佳答案
您的代码 does not compile因为 T...
是无效的可变参数扩展,因为 T
不是参数包。
您的代码还有其他几个问题。我将在下面的代码片段中解决它们:
template <typename T>
class Myclass
{
public:
// `sum` needs to be initialized to a value, otherwise its value
// will be undefined.
T sum = 0;
// `TRest...` is a template variadic type pack.
template <typename... TRest>
T func(T A, TRest... B)
{
sum+=A;
// You need to return from the recursive case of `func`.
return func(B...);
}
T func(T A)
{
sum+=A;
return sum;
}
};
请注意,TRest...
中匹配的值可以是任何类型。如果你想强制它们成为T
,你可以使用下面的技术(或static_assert
):
template <typename...>
using force_to_t = T;
// ...
T func(T A, force_to_t<TRest>... B)
{
sum+=A;
// You need to return from the recursive case of `func`.
return func(B...);
}
感谢 to Piotr's answer,我学会了这个解决方案关于另一个问题。
关于c++ - 可变类模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40801252/