c++ - 如何访问参数包中的第一个参数?

标签 c++ templates variadic-templates

是否可以在编译时静态地“展开”参数列表,在每个“展开”步骤中使用一个参数?我认为可变参数模板是与部分模板特化相结合的方式,但我无法运行此示例:

#include <iostream>

char static const text1[] = "Foo";
char static const text2[] = "FooBar";

template <char const * TEXT, unsigned int N, char const *... REST, unsigned int... Ns>
void doStuff() {
    std :: cout << TEXT << "-" << N << std :: endl;
    doStuff<REST..., Ns...>();
} 

template <char const * TEXT, unsigned int N>
void doStuff() {
    std :: cout << TEXT << std :: endl;
} 

void doStuff() {}

int main() {
    doStuff<text1,3,text2,5>();
    return 0;
}

我的预期输出是 Foo-3\nFooBar-5 然而,clang++ 3.8 给了我:

error: no matching function for call to 'doStuff'
        doStuff<text1,3,text2,5>();
        ^~~~~~~~~~~~~~~~~~~~~~~~
test.cpp:7:6: note: candidate template ignored: invalid explicitly-specified argument for template
      parameter 'REST'
void doStuff() {
     ^
test.cpp:13:6: note: candidate template ignored: invalid explicitly-specified argument for template
      parameter 'N'
void doStuff() {
     ^

最佳答案

在 C++17 中,你可能会做类似的事情

template <char const * TEXT, unsigned int N>
void doStuff() {
    std::cout << TEXT << "-" << N << std::endl;
} 

template <auto v1, auto v2, auto ... values>
void doStuff()
{
    std :: cout << v1 << "-" << v2 << std :: endl;
    doStuff<values...>();
}

目前你必须成对打包你的值:

template<const char* S, int N>
struct pairValue {
     static constexpr const char* s = S;
     static constexpr int n = N;
};

template <typename ... Ts>
void doStuff()
{
    const int dummy[] = {0, ((std::cout << Ts::s << "-" << Ts::n << std::endl), 0)...};
    static_cast<void>(dummy); // Avoid warning for unused variable.
}

并称它为:

 doStuff<pairValue<text1, 3>, pairValue<text2, 5>>();

关于c++ - 如何访问参数包中的第一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38462819/

相关文章:

c++ - 获取 optarg 作为 C++ 字符串对象

c++ - 模块化功能背后的逻辑

c++ - 模板参数推导(在同一调用中同时使用显式和隐式参数)

c++ - 如何防止可变参数构造函数优于复制构造函数?

c++ - 文件只读取 1 条记录,然后到达文件末尾,即使还有其他记录

android - 使用 native CocosDenshion、cocos2d-x 循环播放音效时,AudioFlinger 无法创建音轨,状态为 : -12 ,

javascript - 在 Node/Express 中使用 Pug 模板引擎进行动态模板渲染

c++ - 使用 SFINAE 检查模板参数继承

C++ - 如何从可变数量的基数中引入重载集。

c++ - 带有 'using' 的可变参数模板和类型定义