Is constexpr useful for overload

后端 未结 3 2041
有刺的猬
有刺的猬 2021-01-21 23:52

Is there a way in c++ to get a different overload called based on the runtime/compile time constness of an input? My version(12) of MSVC can\'t do this using constexpr. Reading

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-22 00:22

    constexpr can only be applied to variables and functions, but not function parameters (details on cppreference). Furthermore, you cannot overload the function on whether it is computed at compile or run-time, i.e. this is not valid:

    constexpr int Flip4(int n) {
        return ((n & 0xFF) << 24) | ((n & 0xFF00) << 8) | ((n & 0xFF0000) >> 8) | ((n & 0xFF000000) >> 24);
    }
    
    inline int Flip4(int n) {
        return _byteswap_uint64(n);
    }
    

    One way is to give the functions different names and call them accordingly.

    Just as a side note,

    A constexpr specifier used in a function declaration implies inline.

    So you don't need to declare your constexpr function inline

    Also, don't forget that constexpr functions are only guaranteed to be evaluated at compile-time if they are used in a context required at compile time. So to force it you would need to write:

     constexpr int a = Flip4('abcd');
    

提交回复
热议问题