1

What is wrong with deducing N template parameter in the code below?

enum class Level
{
    Debug,
    Trace,
    Info,
    Action,
    Warning,
    Error
};

template <class Enum, size_t N>
const char* enumValueToString(Enum val, const char* names[N])
{
    return names[static_cast<std::underlying_type_t<Enum>>(val)];
}

const char* m_logLevels[] = { "debug", "trace", "info", "action", "warning", "error" };

const char* logLevelToString(Level t)
{
    return enumValueToString(t, m_logLevels);
}

MSVC compiler error:

error C2784: 'const char *`anonymous-namespace'::enumValueToString(Enum,const char *[N])': could not deduce template argument for 'const char *[N]' from 'const char *[6]'
Dmitriano
  • 1,878
  • 13
  • 29
  • 2
    Change `const char* names[N]` to `const char* (&names)[N]`? (As explained in https://stackoverflow.com/questions/5724171/passing-an-array-by-reference) – UnholySheep Sep 09 '21 at 16:04
  • 2
    When you pass an array by its name only, it *decays* into a pointer to the 1st element, and information about the array's type is lost. That is why `N` can't be deduced. So you have to pass the array by reference instead to preserve the array's type so that `N` can then be deduced. – Remy Lebeau Sep 09 '21 at 16:21
  • @RemyLebeau: It’s more fundamental than that: the type of every specialization of the function template is `const char*(…,const char**)`, so there’s no `N` to deduce. It’s not like you have to *pass* an array differently to a reference parameter. – Davis Herring Sep 10 '21 at 02:26

0 Answers0