我構建了一個指向函數的接口。有時,這種計算取決於狀態,我想在一個類來封裝,並通過其方法: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;
}
但是,這並不顯得優雅給我。我可以編寫一個接受函數指針和非靜態方法的模板嗎?或者我的問題有更好的設計模式嗎?
號因爲對於一個非靜態你需要一個類的實例的方法...爲什麼你需要有這樣的功能?如果你的方法不需要該類的一個實例,使它成爲靜態的,otherwize我不明白你怎麼可以有一個函數可以使用兩個...? – Holt
看看'std :: function',lambdas,'std :: bind'和它們的組合。 – GManNickG
您應該可以使用['std :: bind'](http://en.cppreference.com/w/cpp/utility/functional/bind) – NathanOliver