c++ - 可变参数模板,获取函数参数值

标签 c++ c++11 variadic-templates variadic-functions

我的问题如下: 我有一个这样声明的类:

template<typename ReturnType, typename... Args>
class API
{
    ReturnType operator()(Args... args)
    {
       // Get argument 0
       // Get argument 1
    }
};

我需要一个一个地获取参数,到目前为止我想出的唯一方法(但我无法让它工作)是使用 std::get ,因此:

std::get<0>(args);

当然,这会导致很多错误。 我是可变参数模板(以及 C++11 的新手)所以在这一点上我很迷茫。

我怎样才能一个一个地得到这些参数? 任何帮助将不胜感激。

最佳答案

在临时元组 (Live at Coliru) 中捕获参数:

ReturnType operator()(Args... args)
{
   static_assert(sizeof...(args) >= 3, "Uh-oh, too few args.");
   // Capture args in a tuple
   auto&& t = std::forward_as_tuple(args...);
   // Get argument 0
   std::cout << std::get<0>(t) << '\n';
   // Get argument 1
   std::cout << std::get<1>(t) << '\n';
   // Get argument 2
   std::cout << std::get<2>(t) << '\n';
}

std::forward_as_tuple 使用完美转发来捕获对 args 的引用,因此不应该有复制。

关于c++ - 可变参数模板,获取函数参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565578/

相关文章:

c++ - 如何在 MINGW 中使用 __uuidof?

c++ - 模板类运算符重载多个类型名 C++

c++ - 创建 C++ std::tuple 投影函数

c++ - 单个函数的两个可变参数模板?

c++ - 使用模板模板参数专门化基类

c++ - 在 C++ 中为游戏对象设计类层次结构

c++ - 为什么无堆栈协程需要动态分配?

c++ - 移除 vector 元素使用 vector<bool> 中的条件

c++ - move 构造函数和 move 赋值运算符与复制省略

c++ - 引用或指针更快吗?