c++ - 生成代码以实例化具有不同参数的函数模板

标签 c++ templates c-preprocessor c++14 template-instantiation

给定以下代码:

#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;
}

我想为 XY 的不同组合实例化 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/

相关文章:

c++ - 模板参数作为返回类型

c++ - STL deque 实现的每个 "vectors"是否总是具有相同的大小?

c++ - 包含目录中的所有文件?

C++ 不允许我使用结构作为模板参数

c++ - 使用模板类的 Cast 运算符

c++ - OpenCV 模板化代码在派生类中产生编译错误

javascript - 对所有页面使用相同的 Handlebars 模板

c++ - 让主程序知道资源在哪里(图像、数据……)

C, 是否可以将宏分配给结构变量?

C++简单编写与编译