将模板参数插​​入ostream

时间:2015-03-01 18:34:05

标签: c++ metaprogramming compile-time

我正在尝试设计一个带有参数包(即字符)的可变参数模板,并将这些字符立即插入到cout中。我想我可以使用一个名为PrintChars的结构,并进行某种模板递归来访问参数包中的每个参数。我已经成功在运行时执行此操作,但现在我想在编译时执行此操作。我想举例说明以下模板调用在终端中打印“foo”。

cout << PrintChars<'f', 'o', 'o'>()

你有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:2)

这只是处理参数包的一个简单练习。我的PrintChars<...>确实没有任何状态,它只是传递参数包。

http://ideone.com/39HcTG

#include <iostream>
using namespace std;

template<char... s>
struct PrintChars {};

std::ostream& operator<< (std::ostream& o, const PrintChars<>&)
{
    return o;
}

template<char head, char... tail>
std::ostream& operator<< (std::ostream& o, const PrintChars<head, tail...>& pc)
{
    o << head << PrintChars<tail...>();
    return o;
}

int main() {
    cout << PrintChars<'f', 'o', 'o'>();
    return 0;
}

唯一的元编程&#39;这是在创建正确嵌套的operator<<调用。