如何根据 constexpr 结果在编译时选择函数

Pri*_*tic 2 c++ c++11

我有一个在运行时处理动态数据(many_things)的函数:

void do_some_work(Thing &many_things)
{
    constexpr bool add = something_evald_at_compile_time;

    // do some work
    for(auto &thing : many_things) {
        thing.result = add_or_subtract(thing.one,thing.two);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要有两种“add_or_subtract”变体,并根据 constexpr“add”调用其中之一:

template <typename N> // call me if 'add' == true
N add_or_subtract(N a, N b) { return a+b; }

template <typename N> // call me if 'add' == false
N add_or_subtract(N a, N b) { return a-b; }
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

R S*_*ahu 5

创建一个辅助类型。

template <bool val=true> struct is_add {};
template <> struct is_add<false> {};
Run Code Online (Sandbox Code Playgroud)

使用辅助类型来区分加法和减法。

template <typename N> // call me if 'add' == true
N add_or_subtract(N a, N b, is_add<true>) { return a+b; }

template <typename N> // call me if 'add' == false
N add_or_subtract(N a, N b, is_add<false>) { return a-b; }
Run Code Online (Sandbox Code Playgroud)

用法:

void do_some_work(Thing &many_things)
{
    constexpr bool add = something_evald_at_compile_time;

    // do some work
    for(auto &thing : many_things) {
        thing.result = add_or_subtract(thing.one,thing.two, is_add<add>());
    }
}
Run Code Online (Sandbox Code Playgroud)

对于 C++17,您可以研究if constexpr().