将函数参数声明为 constexpr

问题描述 投票:0回答:1

我能做什么最接近将

constexpr
作为函数输入参数传递?


template<typename T>
void A<T>::foo(int i){ ... }

template<>
void A<X>::foo(constexpr int i){ // I am aware that this does not compile
  trace_stream << "a->foo("<<num_trials<<");\n";
}

在示例中,我必须断言生成跟踪的值

i
将不依赖于调用
A<X>::foo
期间的运行时。

很明显,我可以通过使用模板来实现所需的行为。但是,这将需要对每个出现的

i
值重新编译或预编译上述代码。

c++ templates constexpr
1个回答
0
投票
template<typename T>
void A<T>::foo(int i) { /* Default behavior */ }

template<>
void A<X>::foo(const int i) {
    // Handle specific cases for different i values using macros
    #define HANDLE_CONSTEXPR_I(i) \
        if constexpr (i == 1) { \
            trace_stream << "a->foo(1);\n"; \
        } else if constexpr (i == 2) { \
            trace_stream << "a->foo(2);\n"; \
        } // ... and so on

    HANDLE_CONSTEXPR_I(i)

    #undef HANDLE_CONSTEXPR_I
}

//宏HANDLE_CONSTEXPR_I用于在编译时处理i值的不同情况。虽然使用宏有其局限性和潜在缺点,但它提供了一种处理编译时常量的方法,而无需为每个 i 值生成单独的代码

© www.soinside.com 2019 - 2024. All rights reserved.