views:

66

answers:

2

Just a general c++ curiosity:

This code below shouldn't compile because it's impossible to know which to instantiate: temp(const int&) or temp(const string&) when calling func(temp) - this part i know.

What i would like to know is if there is anything i can do to the line marked PASSINGLINE to get the compiler to deduce that i want FPTR1 called and not FPTR2 ?

#include<iostream>
using std::cout;
using std::endl;

/*FPTR1*/ void func(void(*fptr)(const int&)){ fptr(1001001);} 

/*FPTR2*/ void func(void(*fptr)(const string&)){ fptr("1001001"); } 

template <typename T>
void temp(const T &t){  cout << t << endl; }

int main(){
    /*PASSINGLINE*/ func(temp); 
    return 0;
}

Thank you.

+2  A: 

You can use a static_cast:

func (static_cast <void(*)(const int&)> (&temp));

Tested with GCC 4.x.

doublep
Well, it does work for me on GCC 4.x. What compiler?
doublep
@Loud can you please elaborate? It looks valid to me.
Johannes Schaub - litb
it does work, just tried it. Thanks.
LoudNPossiblyRight
+2  A: 
func(temp<int>);

There's no way to make the compiler infer the template argument, that is more succinct or clearer than just explicitly specifying it, in this case.

Edit: The following code compiles without warning and produces the expected result:

#include<iostream>
#include<string>
using std::string;
using std::cout;
using std::endl;

/*FPTR1*/ void func(void(*fptr)(const int&)){ fptr(1001001);}

/*FPTR2*/ void func(void(*fptr)(const string&)){ fptr("1001001"); }

template <typename T>
void temp(const T &t){  cout << t << endl; }

int main(){
    /*PASSINGLINE*/ func(temp<int>);
    return 0;
}
sepp2k
@Loud: I guess you are confused by errors in your question's code. The answer works fine on GCC 4.x.
doublep
@LoudNPossiblyRight: Works perfectly well for me.
sepp2k