Sign in to follow this  

Why doesn't this work? (templates)

This topic is 4306 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

template <typename X> struct Y
 {
  template <int Z> void foo(void) const
   {}
 };

template <typename X> void operator ! (const Y<X> &a)
 {
  a.foo<42>(); // This line doesn't work.
 }

int main()
 {
  Y<void>().foo<42>(); // Yet line does.
 }

g++ gives me the following error: In function `void operator!(const Y<X>&)': somefile:9: error: expected primary-expression before ')' token Why doesn't it work?

Share this post


Link to post
Share on other sites
Actually, it compiles if I pass an argument. This code compiles: a.foo<42>(void());

That seems insanely stupid. Is there a rational reason why that needs to be done, or is it a bug with with the compiler's parser?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Enigma
a.template foo<42>();

?nigma


Huh. Haven't seen anything like that before. Can you tell me what that means, or at least what it's called so I can look it up?

Share this post


Link to post
Share on other sites
Not sure what name it would go under, but it's required in similar circumstances as you would require the 'typename' keyword. That is, because the class Y has been templated on a template parameter, the compiler cannot know what 'foo' is when it compiles operator!() because it doesn't know what X is. With a combination of the 'template' keyword and the parenthesis, you're telling the compiler that 'foo' is a templated function. Without the 'template' keyword the compiler isn't expect template arguments and would read the line as a.foo less-than 42 greater-than empty-brackets, so it borks.

The reason that Y<void>().foo<42>(); works is because the compiler knows what void is and can work out which specialisation of Y it should be using, thus knowing that foo is a templated function.

Similar code may also work in older compilers, but only because they make assumptions that *aren't* stated in the C++ standard, which is bad.

Share this post


Link to post
Share on other sites

This topic is 4306 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this