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" ?
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.
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.
A template is instantiated the first time it is needed (in the translation unit), not each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With