可变参数模板类的构造函数无法接受变量参数
Variadic template class's constructor fails to accept variable argument
我试图了解可变参数模板的工作原理。 在下面的示例中,我想将变量参数传递给类的构造函数,并将其存储到稍后可以使用的元组中。
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;
}
在线编译器
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 扩展可变参数模板中的变量名称
- 在类构造函数中定义结构变量的参数
- 带有整数的变量参数列表
- 转发变量参数列表以模拟 std::thread
- 如何在不传递命令行参数的情况下在 c++ 中设置环境变量
- 存储稍后要转发的变量参数
- C++具有模板成员变量的类. 和参数内存输出
- 我应该如何在没有变量的情况下将相同的参数传递给 CMAKE 中的多个目标?
- 为变量模板的每个参数调用模板函数
- 具有推导参数的模板函数指针数组变量
- 函数参数变量总是需要 & 或 * 运算符吗?
- 为什么 beginthreadex 线程参数变量在父线程中没有更新
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 如何在函数中使用非参数变量?
- 即将将引用作为函数中的参数传递以更改参数变量的值
- 基于不断变化的参数/变量的XML get值
- cocos2d-x v3 CallFunc作为参数/变量如何
- 在编译时使用c++元编程中的运行时参数(变量)
- 我可以返回一个非参数变量吗?