Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default template argument in method hidden behind class default template argument

Tags:

c++

templates

#include <iostream>

template< typename T = char >
struct Foo {
        void bar();
};

template< typename T = int >
void Foo< T >::bar() {
    std::cout << typeid( T ).name() << std::endl;
}

int main() {
    Foo<> x1;
    Foo< double > x2;
    x1.bar();
    x2.bar();
}

Output:

char
double

char is hiding the int here, why is that?

Is it even possible to have multiple different template arguments for the same class? (Guess not)But why doesn't yell the compiler then?


http://connect.microsoft.com/VisualStudio/feedback/details/892125/ill-formed-default-template-argument-not-throwing-error

like image 761
nonsensation Avatar asked Feb 28 '26 19:02

nonsensation


1 Answers

ill-formed snippet

The code provided in your post is ill-formed as stated by the C++ Standard (n3337):

14.1p9 Template parameters [temp.param]

A default template-argument is a template-argument (14.3) specified after = in a template-paraemter. A default template-argument may be specified for any kind of template-parameter (type, non-type, template) that is not a template parameter pack (14.5.3). A default template-argument may be specified in a template declaration. [ Note: >>] A default template-argument shall not be specified in the template-parameter-lists of the definition of a member of a class template that appears outside of the member's class. [ << :Note ]


Conclusion

With the above quotation in mind we can draw the conclusion that the compiler you are using is faulty; it's not conformant to the rules set out by the Standard, the snippet should not be accepted.


What are the reason behind the Standard disallowing such construct?

Honestly this most probably boils down to "well, it doesn't make sense to allow it".

Since the type of x1 (and with that the type of T) is known at the type of declaration (Foo<> => F<char>), a potential default template-argument when defining a member of the class is useless; it will never be required, nor will it be used.

like image 80
Filip Roséen - refp Avatar answered Mar 02 '26 10:03

Filip Roséen - refp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!