【发布时间】:2021-08-13 16:04:01
【问题描述】:
我试图在一个类中存储一个引用元组(通过可变参数模板),然后我想“循环”它们并为它们赋值。
下面的函数process2 按预期工作,但我想让函数process1 工作相同(利用类本身的存储引用)。但是,我无法编译 process1。正确的方法是什么?有没有办法让成员 Args&... args; 而不是 std::tuple<Args&...> args (因为这可能允许参数扩展)?任何建议表示赞赏。
示例代码:
#include <tuple>
#include <string>
#include <iostream>
template<class... Args>
class Handler
{
private:
template <class T>
static bool process_arg(T& val)
{
if constexpr (std::is_same_v<T, int>)
val = 123;
else if constexpr (std::is_same_v<T, std::string>)
val = "string";
else
{
// do something
return false;
}
return true;
}
public:
const std::tuple<Args&...> args;
Handler(Args&... args)
: args(args ...) { }
// bool process1() const
// {
// // Compile Error: operand of fold expression has no unexpanded parameter packs
// const bool success = (process_arg(args) && ...);
// // Compile Error: no matching function for process_arg(int&, int&, std::string&)
// bool success = true;
// std::apply([&success](auto &&... v) { success = success && process_arg(v...); }, args);
// return success;
// }
template<class... Args2>
static bool process2(Args2&... args2)
{
const bool success = (process_arg(args2) && ...);
return success;
}
};
int main()
{
int a, b;
std::string c;
// Handler(a, b, c).process1();
Handler<>::process2(a, b, c);
std::cout << a << "," << b << "," << c << "\n";
return 0;
}
【问题讨论】:
标签: c++ c++17 variadic-templates