c++ - 可变类模板

标签 c++ c++11

我在编译这段代码时遇到问题。

我想要做的就是创建一个可变参数类模板,它可以为我提供传入的所有元素的总和(例如 1,2,3,4,5,6 应该为 21)无论它是 intfloat。我基本上可以用两个函数模板递归地完成它,我得到了正确的答案,但是当我在类里面实现它时,它没有给我答案。

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;
    }
};

working wandbox example


请注意,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/

相关文章:

c++ - 如何使用 WriteFile 写入 stderr

c++ - 在 C++ Core Guidelines Per.4 中,为什么坏示例旨在更快?

c++ - 如何让-1==-1.0000000000001

c++ - 如何在函数指针中模板化参数?

Mac 上的 C++ : linker command failed with exit code 1 (use -v to see invocation)

c++ - 枚举类 : does not name a value error

c++ - std::move 在堆栈对象上

c++ - 基于空终止字符串的for循环范围

g++ - 如何在centos上指定c++0x标志

c++ - Lambda 和映射,通过引用传递参数 - 编译错误