2016-06-20 52 views
0

我構建了一個指向函數的接口。有時,這種計算取決於狀態,我想在一個類來封裝,並通過其方法:C++函數接受函數指針和非靜態成員函數作爲參數

#include <iostream> 


class Printer { 
public: 
    static void print(int i) { // Want to get rid of the static 
     std::cout << i << "\n"; 
    } 
}; 


template<typename int_func> 
void with_1(int_func func) { 
    func(1); 
} 


int main(int argc, char const *argv[]) { 
    Printer printer; 
    with_1(printer.print); 
    return 0; 
} 

我需要非靜態方法(甚至寧願超載operator())。但是請刪除error: a pointer to a bound function may only be used to call the function中的靜態結果。

我可以用這樣的假:

Printer printer; 
void dummy(int i) { 
    printer.print(i); 
} 


int main(int argc, char const *argv[]) { 
    with_1(dummy); 
    return 0; 
} 

但是,這並不顯得優雅給我。我可以編寫一個接受函數指針和非靜態方法的模板嗎?或者我的問題有更好的設計模式嗎?

+0

號因爲對於一個非靜態你需要一個類的實例的方法...爲什麼你需要有這樣的功能?如果你的方法不需要該類的一個實例,使它成爲靜態的,otherwize我不明白你怎麼可以有一個函數可以使用兩個...? – Holt

+3

看看'std :: function',lambdas,'std :: bind'和它們的組合。 – GManNickG

+1

您應該可以使用['std :: bind'](http://en.cppreference.com/w/cpp/utility/functional/bind) – NathanOliver

回答

1

你不能簡單地通過這樣的非靜態方法,因爲它們在實例上工作。一個簡單的解決方案是使用拉姆達:

#include <iostream> 


class Printer { 
public: 
    static void print(int i) { // Want to get rid of the static 
     std::cout << i << "\n"; 
    } 
}; 


template<typename int_func> 
void with_1(int_func func) { 
    func(1); 
} 


int main(int argc, char const *argv[]) { 
    Printer printer; 

    // Can use capture by reference because we are sure printer still 
    // exist during execution of with_1 
    with_1([&printer](int i){ printer.print(i); }); 

    return 0; 
} 

example

1

試試這個:

int main(int argc, char const *argv[]) { 
    Printer printer; 
    with_1(std::bind(&Printer::print, printer, std::placeholders::_1)); 
    return 0; 
} 

(你需要#include <functional>。)

+0

其實我更喜歡用一些純函數來綁定某些函數,謝謝指出:-) – qiv

相關問題