c++ - Variadic 模板类的构造函数无法接受可变参数

标签 c++ parameter-passing c++14 variadic-templates variadic-functions

我想了解可变参数模板的工作原理。 在下面的示例中,我想将变量参数传递给类的构造函数并将其存储到一个元组中,以供稍后使用。

template<typename... Args>
class CompoundOrs
{
public:
    CompoundOrs(){}

    CompoundOrs(Args... args) {
        m_tuple_args = std::tuple<Args...>(args...);
    }

    virtual bool eventPredicate() {
        return unpack_tuple(m_tuple_args, std::index_sequence_for<Args...>());
    }

    bool iterativeOr(bool evt) {
        return evt;
    }

    bool iterativeOr(bool evt, Args... args) {
        return (evt || iterativeOr(args...));
    }

    template<std::size_t... Is>
    bool unpack_tuple(const std::tuple<Args...>& args, std::index_sequence<Is...>) {
        return iterativeOr(std::get<Is>(args)...);
    }

private:
    std::tuple<Args...> m_tuple_args;
};
int main()
{
    bool a = true;
    bool b = false;
    bool c = true;
    CompoundOrs<bool> c_or(a, b, c);

    return 0;
}

这会引发编译错误,指示参数不匹配。我在某处读到,我的基函数的声明顺序也很重要,这就是为什么我将空构造函数添加为第一个构造函数,但这也无济于事。

main.cpp: In function 'int main()':
main.cpp:64:33: error: no matching function for call to 'CompoundOrs::CompoundOrs(bool&, bool&, bool&)'
     CompoundOrs<bool> c_or(a,b,c);
                                 ^
main.cpp:28:5: note: candidate: CompoundOrs::CompoundOrs(Args ...) [with Args = {bool}]
     CompoundOrs(Args... args)
     ^
main.cpp:28:5: note:   candidate expects 1 argument, 3 provided
main.cpp:19:1: note: candidate: CompoundOrs::CompoundOrs() [with Args = {bool}]
 CompoundOrs()
 ^
main.cpp:19:1: note:   candidate expects 0 arguments, 3 provided
main.cpp:15:7: note: candidate: constexpr CompoundOrs::CompoundOrs(const CompoundOrs&)
 class CompoundOrs
       ^
main.cpp:15:7: note:   candidate expects 1 argument, 3 provided
main.cpp:15:7: note: candidate: constexpr CompoundOrs::CompoundOrs(CompoundOrs&&)
main.cpp:15:7: note:   candidate expects 1 argument, 3 provided

最佳答案

这可以简化为

#include <tuple>
template<typename... Args>
class CompoundOrs
{
    private: std::tuple<Args...> m_tuple_args;

    // template constructor accepting another set of arguments
    // and forwarding them to tuple field constructor.
    public: template<typename... InnerArgs>
    CompoundOrs(InnerArgs &&... args) : m_tuple_args{::std::forward<InnerArgs>(args)...} {}
};
int main()
{
    bool a = true;
    bool b = false;
    bool c = true;
    CompoundOrs<bool, bool, bool> c_or(a, b, c);

    return 0;
}

online compiler

关于c++ - Variadic 模板类的构造函数无法接受可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51800272/

相关文章:

c++ - "template<>"vs "template"没有括号 - 有什么区别?

c++ - 获取数字的一部分

java - Java中方法参数的线程安全

c++ - 如何使用非平凡构造函数构造静态 thread_local 成员

c++ - 如何存储类型以供以后比较

php - 尝试从 C++ 运行 https 代码时 SSL 握手失败

c++ - 派生类型的成员

delphi - 我可以将类类型作为过程参数传递吗

c - 从函数中获取数组的计数

c++ - 来自 Boost.Spirit 语法的属性:来自 std:vector of boost::variant 的错误