Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SFINAE gets messed up when changing the place of the class template specialization? Is this a C++ bug?

Following code gives compiler error which is expected (Demo):

  1 template<bool> struct Range;
  2 
  3 template<int value, typename = Range<true> > struct Unique;
  4 template<int value> struct Unique<value, Range<(value > 1)> > { typedef char type[1]; };
  5 template<int value> struct Unique<value, Range<(value > 2)> > { typedef char type[2]; };
  6 
  7 Unique<3>::type o1;
  8 Unique<3>::type o2;

Now, if I swap line-5 and line-7. Then there is NO compiler error !! Demo.

  5 Unique<3>::type o1;

  7 template<int value> struct Unique<value, Range<(value > 2)> > { typedef char type[2]; };

For o1, it's understandable to have no error, because specialization for (value > 2) is not yet visible. But why there no error for o2 also, which sees 2 matching specializations !?
My guess is that, compiler should be choosing the Unique<3>::type with some arbitrary name when it encounters for the 1st time and then replacing Unique<3>::type everywhere with that name.

Is this a compilation bug or C++ bug or C++ "feature" ?

like image 621
iammilind Avatar asked Mar 06 '12 10:03

iammilind


People also ask

Is specialization of template C++?

It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming.

What is called specialization in template?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.


1 Answers

A template is instantiated the first time it is needed (in the translation unit), not each time.

like image 196
James Kanze Avatar answered Sep 21 '22 22:09

James Kanze