可变参数模板类的构造函数无法接受变量参数

Variadic template class's constructor fails to accept variable argument

本文关键字:参数 变量 构造函数 变参      更新时间:2023-10-16

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

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

在线编译器