Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将模板参数插入到ostream中_C++_Metaprogramming_Compile Time - Fatal编程技术网

C++ 将模板参数插入到ostream中

C++ 将模板参数插入到ostream中,c++,metaprogramming,compile-time,C++,Metaprogramming,Compile Time,我正在尝试设计一个可变模板,它接受一个参数包(即字符),并将这些字符立即插入cout。我设想我可以使用一个名为PrintChars的结构,并执行某种模板递归来访问参数包中的每个参数。我已经在运行时成功地做到了这一点,但现在我想在编译时做到这一点。例如,我希望使用以下模板调用在终端中打印“foo” cout << PrintChars<'f', 'o', 'o'>() cout这只是处理参数包的一个简单练习。我的PrintChars实际上没有任何状态,它只是传递参数包

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

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

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

#包括
使用名称空间std;
模板
结构PrintChars{};

std::ostream&operator您计划如何在编译时
cout
?哎呀,您是对的。我首先需要在编译时将这些字符存储在结构中,然后在运行时将其写入输出流。有什么办法吗?要打印存储为模板参数包的一些字符,可以将它们存储在数组中:
constexpr static char arr[]={character_pack…}
或使用包扩展技巧之一调用
cout
#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;
}