Jump to content
  • Advertisement
Sign in to follow this  
smart_idiot

Why doesn't this work? (templates)

This topic is 4519 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
Advertisement
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
I think I saw the a.template foo<42> () problem at C++ Standard Library Active Issues List but haven't crushed one before, your code compiles fine on VS 2003.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!