4By*_*tes 5 c++ templates c-preprocessor
如何使用预处理器条件编译模板功能?像那样(但它不起作用):
template <bool var>
void f()
{
#if (var == true)
// ...
#endif
}
Run Code Online (Sandbox Code Playgroud)
你不能用预处理器做到这一点.您所能做的就是将代码委托给一个单独的模板,如下所示:
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一个类并将共享数据存储在其中.