【问题标题】:Inserting template parameters into ostream将模板参数插​​入 ostream
【发布时间】:2015-05-02 01:44:47
【问题描述】:

我正在尝试设计一个可变参数模板,该模板采用参数包(即字符)并将这些字符立即插入 cout。我想象我可以使用一个名为 PrintChars 的结构并执行某种模板递归来访问参数包中的每个参数。我已经在运行时成功地做到了这一点,但现在我想在编译时做到这一点。例如,我希望在终端中调用以下模板来打印“foo”。

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

你有什么想法吗?谢谢。

【问题讨论】:

  • 编译时你打算如何cout
  • 糟糕,你是对的。我首先需要在编译时将这些字符存储在结构中,然后在运行时将其写入输出流。任何想法如何做到这一点?
  • 要打印一些作为模板参数包存储的字符,您可以将它们存储在一个数组中:constexpr static char arr[] = {character_pack...}; 或使用包扩展技巧之一为每个字符调用cout &lt;&lt; one_character:@ 987654321@

标签: c++ metaprogramming compile-time


【解决方案1】:

这只是处理参数包的一个简单练习。我的PrintChars&lt;...&gt; 没有任何状态,它只是传递参数包。

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;
}

这里唯一的“元编程”是创建正确嵌套的operator&lt;&lt; 调用。

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多