代码之家  ›  专栏  ›  技术社区  ›  LoudNPossiblyWrong

传递模板func。作为一个函数。指向过载函数的指针。-有没有编译这段代码的方法?

  •  0
  • LoudNPossiblyWrong  · 技术社区  · 14 年前

    只是一个普通的C++好奇心:

    下面的代码不应该编译,因为不可能知道要实例化哪个代码: temp(const int&)或temp(const string&) 打电话给func(临时)-这部分我知道。

    我想知道的是,如果我能对标记的行做些什么 传球路线 让编译器推断出 FPTR1 召唤而不是 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;
    }
    

    谢谢您。

    2 回复  |  直到 14 年前
        1
  •  2
  •   sepp2k    14 年前
    func(temp<int>);
    

    没有办法让编译器推断出模板参数,在本例中,这比显式地指定模板参数更简洁或清晰。

    编辑:以下代码编译时不发出警告,并生成预期结果:

    #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;
    }
    
        2
  •  2
  •   doublep    14 年前

    你可以使用 static_cast :

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

    用GCC 4.x测试。