【发布时间】:2017-11-25 08:10:42
【问题描述】:
给定以下代码:
#include <iostream>
template <int X, int Y>
int foo(int v) // dummy parameter
{
return v * X + v / Y; // dummy calculation
}
int main()
{
// x, y, v are only known at runtime
int x = 4;
int y = 6;
int v = 3;
int result = 0;
if (x == 1 && y == 1) result = foo<1, 1>(v);
if (x == 1 && y == 3) result = foo<1, 3>(v);
if (x == 5 && y == 1) result = foo<5, 1>(v);
if (x == 4 && y == 6) result = foo<4, 6>(v);
if (x == 8 && y == 4) result = foo<8, 4>(v);
// ...
std::cout << result << std::endl;
}
我想为X 和Y 的不同组合实例化foo,如main 中的if 级联所示。
然而,这可能会变得非常丑陋(长)。在给定所需组合列表的情况下,是否有可能使用 C++14(例如通过使用预处理器)生成此代码?
【问题讨论】:
-
为什么不使用可变参数模板参数列表,由所需组合对组成?
-
@user0042:我不知道这是可能的。但是避免预处理器的解决方案当然可以。 ;-)
-
Related,可能是骗子。
标签: c++ templates c-preprocessor c++14 template-instantiation