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