给定以下代码:
#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
,如 if
级联所示在 main
中。
然而,这可能会变得非常丑陋(长)。是否有可能使用 C++14(例如,通过使用预处理器)在给定所需组合列表的情况下生成此代码?
最佳答案
这是一个使用递归的版本。
#include <iostream>
#include <utility>
#include <stdexcept>
template <int X, int Y>
int foo(int v) // dummy parameter
{
return v * X + v / Y; // dummy calculation
}
template <std::size_t index = 0>
int foo(int x, int y, int v) {
constexpr std::pair<int, int> numbers[] = {{1, 1}, {1, 3}, {5, 1}, {4, 6}, {8, 4}};
if constexpr (index < sizeof numbers / sizeof *numbers) {
if (numbers[index].first == x && numbers[index].second == y) {
return foo<numbers[index].first, numbers[index].second>(v);
}
return foo<index + 1>(x, y, v);
} else { //no match
throw std::runtime_error("No matching pair found");
}
}
int main() {
// x, y, v are only known at runtime
int x = 4;
int y = 6;
int v = 3;
int result = foo(x, y, v);
std::cout << result << std::endl;
}
如果您没有 C++17,您可以将 if constexpr
替换为标签调度。 Both clang and gcc manage to optimize out the code starting at -O1 .
关于c++ - 生成代码以实例化具有不同参数的函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47483884/