4

Why is the following injecting a constexpr integral into a template not working

#include <iostream>
#include <type_traits>

template<typename E>
static constexpr auto enumToInt(E e) -> typename std::underlying_type<E>::type
{
    return static_cast<typename std::underlying_type<E>::type>(e);
}


template<typename E>
static consteval auto enumToIntC(E e) 
{
    constexpr auto value = enumToInt(e);
    return std::integral_constant<typename std::underlying_type<E>::type, value>{};
}

int main()
{
    enum A{ A,B};
    constexpr auto e = A::A;
    constexpr auto i = enumToInt(e); // works
    constexpr auto c = enumToIntC(e); // does not compile...
}

Why is there a limitation of injecting a clearly constexpr value into template non-type parameter not allowed? I don't understand why there is such a limitation? Is that not compiling because consteval is not yet implemented in clang-10 and decays to constexpr...?

Because this works:

template<int N> struct A {};
constexpr int value = 3;
A<value> b;
Gabriel
  • 8,990
  • 6
  • 57
  • 101
  • 1
    https://stackoverflow.com/questions/56130792/will-consteval-functions-allow-template-parameters-dependent-on-function-argumen – Holt Dec 31 '19 at 13:14
  • 1
    Note that both GCC and Clang first fail on the `constexpr auto value = enumToInt(e);` line, not on the use of `value` as a template parameter, so it is not a *"limitation of injecting a clearly constexpr value into template"*, but rather that you cannot use `e` as a compile-time expression. The above link explains why. – Holt Dec 31 '19 at 13:18
  • 1
    A short quote from [Barry's answer](https://stackoverflow.com/a/56131346/9171697): The return type of `enumToIntC` would essentially be dependent on the parameter you pass...but a single function shall not have multiple return type. – ph3rin Dec 31 '19 at 13:58
  • @Holt But why is e not a compiletime expr. is it not a requirement for evaluating the function that all parameters need to be compile time expressions. This is strange. But with the concern of multiple types and that its not a template it makes sense :). – Gabriel Jan 01 '20 at 13:47

0 Answers0