开发者

Passing a template func. as a func. ptr to an overloaded func. - is there a way to compile this code?

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.


You can use a static_cast:

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

Tested with GCC 4.x.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜