Home > Mobile >  Partial specialiszation of a template class with string template argument
Partial specialiszation of a template class with string template argument

Time:05-22

#include <iostream>

template<unsigned N>
struct FixedString 
{
    char buf[N   1]{};
    constexpr FixedString(const char (&s)[N]) 
    {
        for (unsigned i = 0; i != N;   i)
            buf[i] = s[i];
    }
};

template<int, FixedString name>
class Foo 
{
public:
    auto hello() const { return name.buf; }
};

template<FixedString name>
class Foo<6, name>
{
public:
    auto hello() const { return name.buf; }
};

int main() 
{
    Foo<6, "Hello!"> foo;
    foo.hello();
}

I'm trying to add a template specialisation Foo<6, name> and it ends in this error:

macros.h: At global scope:
macros.h:3:18: error: class template argument deduction failed:
 23 | class Foo<6, name>
      |                  ^
macros.h:3:18: error: no matching function for call to ‘FixedString(FixedString<...auto...>)’
macros.h:7:15: note: candidate: ‘template<unsigned int N> FixedString(const char (&)[N])-> FixedString<N>’
 7 |     constexpr FixedString(const char (&s)[N])
      |               ^~~~~~~~~~~
macros.h:7:15: note:   template argument deduction/substitution failed:
macros.h:13:18: note:   mismatched types ‘const char [N]’ and ‘FixedString<...auto...>’
 23 | class Foo<6, name>
      |                  ^
macros.h:4:8: note: candidate: ‘template<unsigned int N> FixedString(FixedString<N>)-> FixedString<N>’
 4 | struct FixedString
      |        ^~~~~~~~~~~
macros.h:4:8: note:   template argument deduction/substitution failed:
macros.h:13:18: note:   mismatched types ‘FixedString<N>’ and ‘FixedString<...auto...>’
 23 | class Foo<6, name>

What is the proper way to specialise template classes with string template arguments? g (Ubuntu 9.4.0-1ubuntu1~16.04) 9.4.0

CodePudding user response:

What is the proper way to specialise template classes with string template arguments?

The given code is well-formed(in C 20) but fails to compile for gcc 10.2 and lower. It however compiles fine from gcc 10.3 and higher. Demo

Might be due to that not all C 20 features were fully implemented in gcc 10.2 and lower.

  • Related