How to ensure constexpr function never called at runtime?

后端 未结 5 1027
无人及你
无人及你 2020-12-05 18:52

Lets say that you have a function which generates some security token for your application, such as some hash salt, or maybe a symetric or asymetric key.

Now lets sa

5条回答
  •  执念已碎
    2020-12-05 19:11

    Since now we have C++17, there is an easier solution:

    template 
    struct constant {
        constexpr static decltype(V) value = V;
    };
    

    The key is that non-type arguments can be declared as auto. If you are using standards before C++17 you may have to use std::integral_constant. There is also a proposal about the constant helper class.

    An example:

    template 
    struct constant {
        constexpr static decltype(V) value = V;
    };
    
    constexpr uint64_t factorial(int n) {
        if (n <= 0) {
            return 1;
        }
        return n * factorial(n - 1);
    }
    
    int main() {
        std::cout << "20! = " << constant::value << std::endl;
        return 0;
    }
    

提交回复
热议问题