cpp*_*hon 8 c++ templates variadic-templates c++11
我想解压缩参数包func
(参见第A行),但它不起作用.如何在func <>内解包或仅修改A行?
#include <iostream>
using namespace std;
void func()
{
cerr << "EMPTY" << endl;
}
template <class A, class ...B> void func()
{
cerr << "A: " << endl;
func<B... >(); // line A
}
int main(void)
{
func<int,int>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
预期输出:
A:
A:
Run Code Online (Sandbox Code Playgroud)
编辑:所有答案都非常好.非常感谢
Cas*_*sey 12
有时一次解压缩所有内容更容易,而不是递归.如果你只想要一个参数包for_each,你可以使用braced -init-list扩展技巧的变种(Coliru的现场演示):
template <class A>
void process_one_type() {
cerr << typeid(A).name() << ' ';
}
template <class ...B> void func()
{
int _[] = {0, (process_one_type<B>(), 0)...};
(void)_;
cerr << '\n';
}
Run Code Online (Sandbox Code Playgroud)
hps*_*use 10
通过使用func<B... >();
你暗示这func
是一个功能模板,但你之前定义func()
的不是.
您需要定义一个func()
接受零模板参数的模板.这是一个工作示例(在g ++ 4.8.1上):
#include <iostream>
using namespace std;
void func()
{
cerr << "EMPTY" << endl;
}
template <class ... B>
typename std::enable_if<sizeof...(B) == 0>::type func()
{
}
template <class A, class ...B> void func()
{
cerr << "A: " << endl;
func<B... >(); // line A
}
int main(void)
{
func(); // This outputs EMPTY
func<int,int>(); // This will not output EMPTY
return 0;
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
template <class A> void func()
{
cerr << "A: " << endl;
}
template <class A, class B, class ...C> void func()
{
cerr << "A: " << endl;
func<B, C...>(); // line A
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12149 次 |
最近记录: |