A class template specialization in which a template is a template template: the difference is Visual Studio vs. g ++

The following code I got to read this compiles and behaves fine in gcc ( link ), but an error message appears in Visual Studio.

Error C2910 ' my_property<A<U>> ': cannot be explicitly specialized

It works fine only if I delete the line template <> . I got a workaround here . The workaround is fine in g ++ too.

 #include <iostream> #include <type_traits> template <typename T> struct A { T x; }; template <typename T> struct my_property { static const bool value = false; }; template <> //Remove this and it will work in Visual Studio template <typename U> struct my_property<A<U>> { static const bool value = true; }; int main() { std::cout << std::boolalpha; std::cout << my_property<int>::value << '\n'; //false std::cout << my_property<A<int>>::value << '\n'; //true std::cout << my_property<A<float>>::value << '\n'; //true } 

Which compiler is right?

+5
source share
1 answer

If I read the standard correctly, template<> should not be used in this case.

Basically, you need to provide several lists of template options for nested templates:

(see [temp.mem] ยง1)

A template can be declared in a class or class template; such a template is called a member template. Member template can be defined inside or outside the class definition or class template definition. A member template of a class template, which is defined outside the definition of its class, must be specified using the template parameters of the class template , followed by the template parameters of the member template.

... but you should not provide an additional list of template parameters to specialize the template with the template parameter:

(see [temp.class.spec] ยง2)

Each individual template template specialization is a separate template ...

(and then ยง4)

The parameters of the template are indicated in the attached list of angle brackets, which immediately follows the keyword template. For partial specialization, the list of template arguments is explicitly written immediately after the class template name. For primary templates, this list is implicitly described by the list of template parameters ...

There is nothing to offer an additional list of template parameters - specialization is just a template, and as such it requires only one parameter list.

+2
source

Source: https://habr.com/ru/post/1275893/


All Articles