Is it legal to assign a template function to a function pointer this way

C

cindypwl

I was looking at some code in the MS NG, and I saw this code listed.
template <class T>class List{};

template<class T>
bool MySortFunc(List<T>& list){return true;}

template <class T>struct SORT{typedef bool (*FnPtr)(List<T>& list);};

int main(){
List<int> MyList;
List<long> MyList2;
SORT<int>::FnPtr Sort = &MySortFunc; //***No template type!!!!!!!
Sort(MyList);

I would think that the function pointer assignment would not compile
with out using the templae type.
SORT<int>::FnPtr Sort = &MySortFunc<int>;

But I was able to compile this with out the type on both VC++ and
Comeau.

So is this code legal, or are the compilers wrong to compile it
successfully?
 
B

Bob Hairgrove

I was looking at some code in the MS NG, and I saw this code listed.
template <class T>class List{};

template<class T>
bool MySortFunc(List<T>& list){return true;}

template <class T>struct SORT{typedef bool (*FnPtr)(List<T>& list);};

int main(){
List<int> MyList;
List<long> MyList2;
SORT<int>::FnPtr Sort = &MySortFunc; //***No template type!!!!!!!
Sort(MyList);

I would think that the function pointer assignment would not compile
with out using the templae type.
SORT<int>::FnPtr Sort = &MySortFunc<int>;

But I was able to compile this with out the type on both VC++ and
Comeau.

So is this code legal, or are the compilers wrong to compile it
successfully?

It is legal. The compiler instantiates MySortFunc<int> automatically
because it is the only possible candidate. Otherwise, you might have
to disambiguate it. The compiler is very clever in this regard (well,
most modern compilers are, anyway).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,900
Latest member
Nell636132

Latest Threads

Top