预处理程序和模板参数或代码段的条件编译

4By*_*tes 5 c++ templates c-preprocessor

如何使用预处理器条件编译模板功能?像那样(但它不起作用):

template <bool var>
void f()
{
    #if (var == true)
    // ...
    #endif
}
Run Code Online (Sandbox Code Playgroud)

sla*_*ppy 9

你不能.正如此名称所示,预处理器在编译器之前处理源文件.因此,它不知道模板参数的值.


Rei*_*ica 7

你不能用预处理器做到这一点.您所能做的就是将代码委托给一个单独的模板,如下所示:

template <bool var>
void only_if_true()
{}

template <>
void only_if_true<true>()
{
  your_special_code_here();
}


template <bool var>
void f()
{
  some_code_always_used();
  only_if_true<var>();
  some_code_always_used();
}
Run Code Online (Sandbox Code Playgroud)

当然,如果您需要在f()和之间共享信息only_if_true()(很可能),您必须将其作为参数传递.或者创建only_if_true一个类并将共享数据存储在其中.