Search code examples
c++constexprdecltype

How to remove `constexpr` from type of variable


Constexpr seems to be part of a variable's type (received via decltype(...)), as the following assertion fails:

constexpr int variable {};
static_assert(std::is_same_v<int, std::remove_cvref<std::decay<decltype(variable)>>>);

Is there a helper structure in the standard library which I can use on the second argument of is_same_v in order to make the assertion true? I currently use the following workaround which I would like to replace with a proper solution:

template <typename T> T func();
static_assert(std::is_same_v<int, decltype(func<decltype(variable)>())>);

The code is available here; I use this for restricting a non-type template parameter's auto-deduced type.


Solution

  • constexpr only changes the variable's type to const, hence for instance std::remove_cvref_t<...> can be used to "fix" the assertion. Therefore, the following static assertions both compile:

    static_assert(std::is_same_v<int const, decltype(variable)>);
    static_assert(std::is_same_v<int, std::remove_cv_t<decltype(variable)>>);
    

    Due to a typo, the argument in the question's assertion falsely compares the type of the struct remove_cvref with int, as the suffix _t (aliasing to remove_cvref<...>::type) is missing. This type is not the same as int which causes the static_assertion to fail.