Q1)鑑於我們已C++ shared_ptr與std :: function或double(* SOME_NAME)(double);
typedef double (*function_t)(double);
或
typedef std::function<double(double)> function_t;
我們如何定義
std::shared_ptr<function_t> ptr_func = ???
一些功能。
比方說,我們想要一個shared_ptr
到一個已經定義的對象(忘記了它現在失敗的目的 - 但我需要這個)。作爲示例,請考慮以下對於double
類型的對象。
struct null_deleter
{
void operator() (void const *) const {};
};
int main()
{
// define object
double b=0;
// define shared pointer
std::shared_ptr<double> ptr_store;
ptr_store.reset(&b,null_deleter()); // this works and behaves how you would expect
}
雖然如果我們做function_t
類型的shared_ptr
相同,即
double f (double x)
{
// some_function + return
}
int main()
{
// define shared pointer
std::shared_ptr<function_t> ptr_store;
ptr_store.reset(&f,null_deleter()); // ERROR: does not work
}
返回的錯誤是像下面這樣:
error: cannot convert 'double (*)(double)' to 'double (**)(double)' in initialization
或在std::function
的情況下
error: cannot convert 'double (*)(double)' to 'std::function<double(double)>*' in initialization
很顯然不是正確的類型過去了,可能是我們不允許這樣做
注(?):與g++4-7-2
版本-std=c++11 -O3
在Windows編譯MinGW的
的幾個答案做工精良,今天我會回覆你。這是早上6點30分,我還沒有去睡覺。我正在執行的整個設計模式可能是錯誤的,希望稍後我可以解釋一下:|
可能工作的一種方法是std :: bind(&f)。 – 2013-03-27 05:02:21
@Guy這不起作用,或者我得到一個錯誤'失配類型'_Tp1 *'和'std :: _ Bind(double(*())(double))''。但是我會看到我能用'std :: bind'做什麼,之前沒有用過。 – woosah 2013-03-27 05:09:00
我爲你做了一些例子。不知道這是否正是你想要的(或爲什麼你想要它),但它顯示了這些類如何一起玩。 – 2013-03-27 05:15:14