gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:30:20 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com