2015-11-12 67 views
2

我想構建一個具有作爲參數的方法的成員函數的類。這些方法在繼承類中定義。我建一個小例子:將繼承的方法傳遞給另一個方法

#include <iostream> 

struct base 
{ 
    base() {} 

    int number(int (*f)(int)) 
    { 
     return f(1); 
    } 
}; 

struct option1 : base 
{ 
    int timesTwo(int i){return 2*i;} 
    option1() 
    { 
     std::cout << number(timesTwo); 
    } 
}; 

struct option2 : base 
{ 
    int timesThree(int i){return 3*i;} 
    int timesFour (int i){return 4*i;} 
    option2() 
    { 
     std::cout << number(timesThree); 
    } 
}; 

int main() 
{ 
    option1 a; //I would expect this to print "2" 
} 

在功能number目前的語法是一般的功能,但我不能得到它的任何繼承類的方法工作。

回答

5

這裏的問題是,你傳遞一個指向成員功能,這是從指針到一個非成員函數(這是你的number函數有什麼作爲參數)完全不同。

你可以使用std::functionstd::bind

int number(std::function<int(int)> f) 
{ 
    return f(1); 
} 

... 

number(std::bind(&option1::timesTwo, this, _1)); 

您也可以使用模板和額外的參數,如視情況和使用

template<typename T> 
int number(T* object, int(T::*f)(int)) 
{ 
    return (object->*f)(1); 
} 

... 

number(this, &option1::timesTwo); 

或簡單(但並不總是正確的,情況):製作回撥功能static

static int timesTwo(int i){return 2*i;} 

我的建議是,你看看在使用std::function的解決方案,因爲這樣很容易調用number功能與任何類型的可調用的對象,像拉姆達:

number([](int x){ return x * 2; }); 
+0

謝謝!如果我應該擔心只是添加'static'的解決方案,你可以擴展嗎?我明白使用'std :: function'更通用,但我相當肯定我不會在任何其他情況下調用該函數。 – RobVerheyen

+1

@RobVerheyen如果你傳遞的函數永遠不會訪問它定義的類中的任何非靜態成員,那麼你可以使它成爲「靜態」而不用擔心。 –

4

給定的錯誤說:

error: reference to non-static member function must be called

您可以在方法成員之前添加static

而且我建議你使用std::function而不是指針函數。

一個工作代碼:

#include <iostream> 
#include <functional> 

struct base 
{ 
    base() {} 

    int number(std::function<int(int)> f) 
    { 
     return f(1); 
    } 
}; 

struct option1 : base 
{ 
    static int timesTwo(int i){return 2*i;} 
    option1() 
    { 
     std::cout << number(timesTwo); 
    } 
}; 

struct option2 : base 
{ 
    static int timesThree(int i){return 3*i;} 
    static int timesFour (int i){return 4*i;} 
    option2() 
    { 
     std::cout << number(timesThree); 
    } 
}; 

int main() 
{ 
    option1 a; // now it works 
} 
+0

謝謝。特別是在指針上使用'std :: function'是否有任何理由,因爲代碼很可能不再需要上述任何方法? – RobVerheyen

+1

@RobVerheyen你應該看看[那裏](http://stackoverflow.com/questions/25848690/should-i-use-stdfunction-or-a-function-pointer-in-c)和[there](http ://stackoverflow.com/questions/9054774/difference-between-stdfunction-and-a-standard-function-pointer)。這是更多的C++ ish,但你可以堅持你的解決方案。我認爲更重要的是你應該重新設計你的代碼。 – coincoin

相關問題