?

Log in

No account? Create an account
Whoa - Konstantin Savenkov [entries|archive|friends|userinfo]
Konstantin Savenkov

[ website | My Website ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

Whoa [Dec. 8th, 2006|07:22 pm]
Konstantin Savenkov
[Tags|, ]
[Current Mood |impressedimpressed]

I've just got an interesting insight into C++ template programming.

Consider the following class with a template method foo:

class A
{
public:
template<class T>
int foo();
};

template<> int A::foo<int>()
{
return 1;
};

Now imagine that you want to use it in another template (say a template function) in the following way:

template<typename T>
T bar()
{
A a;
return a->foo<T>();
}

Huh? Got error on a->foo<T>()? So am I!

Some time ago I've already stumbled on this situation and decided that this is due to some uncertainty in determining of the actual type of a or something like that. That time I used a->A::foo<T>() workaround and dropped a tear or two on a grave of polymorphism.

Today a collegue of mine asked me to take a look on such construction, and a fresh look (combined with an updated google base:-) ) has brought a new solution:

template<typename T>
T bar()
{
A a;
return a->template foo<T>();
}

Impressed? So am I, again. I just wander, is that some g++-related "feature" or correct ANSI/ISO C++ syntactic construction? (uh, ok, I'm just too lazy to browse the standard).

upd: g++ 4.1.2 doesn't consider the first variant as a syntactic error (looks like the bug in the compiler has been fixed). Nevertheless the latter variant is still amusing to me :-).



crossposted to ru_cpp
LinkReply