c++ - 如何定义可变参数模板的参数?

标签 c++ c++11 templates using type-alias

我有一个可变参数模板,并希望使用 using 别名声明来定义参数。

这是一个例子:

template<class I, class... P>
struct Molecule {
  using Index = I;
};

我的问题是,如何定义 P... 的第一个参数?

我已经尝试过此操作,但它会生成错误:

template<class I, class... P>
struct Molecule {
  using Index = I;
  P array[sizeof...(P)] = { P... };
  using Part1 = array[0];
};

请问有什么建议吗?

最佳答案

how i can define the first argument of P... ?

如果Molecule可以重新定义为以下内容,则可以直接获取:

template<class I, class First, class... P> { 
    using Part1 = First;
    // .....
}

否则,创建一个特征来查找第一种类型:

template<typename First, typename... Rest> 
struct first { using type = First; };
template<typename... Args> using first_t = typename first<Args...>::type;

现在

template<class I, class... P> struct Molecule {  
    using Part1 = first_t<P...>; // first type
};

假设您在可变参数 P... 中至少有一个参数。

<强> See a demo

关于c++ - 如何定义可变参数模板的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72473210/

相关文章:

c++ - 使用 std::accumulate 和 std::string 有效

c++ - Botan编译错误VS2015

c++ - 可变参数模板继承中的类型不匹配

c++ - 如何专门化没有参数的模板类?

c++ - 多层感知器有时不会收敛到正确答案 - XOR

c++ - 运行长度编码(整数)

c++ - C++ 中的多个异步调用

c++ - 成员变量如何与专门的类模板一起使用?

html - 用当前 CSS 替换新的 CSS Sprite

c++ - C++ 初始化中的 *