[英]std::function and shared_ptr
我一直在使用Loki的Functor,我最近問了一個關於它的問題 (仍然沒有答案......)我被告知要使用std :: function,但我更喜歡Loki的Functor實現,因為它也適用於各種各樣的指針作為參數(例如std :: shared_ptr)。
struct Toto
{
void foo( int param )
{
std::cout << "foo: " << param << std::endl;
}
};
int
main( int argc, const char** argv )
{
std::shared_ptr<Toto> ptr = std::make_shared<Toto>();
Loki::Functor<void, LOKI_TYPELIST_1(int)> func( ptr, &Toto::foo );
func(1);
}
有沒有辦法用std :: function做到這一點?
使用std::bind
。
auto func = std::bind(&Toto::foo, ptr, std::placeholders::_1);
在這里, func
將被推斷為類型,從std::bind
返回,或者如果你不喜歡auto
你可以使用(並且你想使用std::function
)
std::function<void(int)> func = std::bind(&Toto::foo,
ptr, std::placeholders::_1);
這里std::function
將根據std::bind
結果構造。 ptr
將被復制到從std::bind
返回的某個對象,但如果你不想復制,你可以使用std::ref
/ std::cref
。
如果你不想使用std::bind
,一個選項就是使用lambda函數,從而產生更小的代碼,我個人覺得它更直觀:
auto func = [&ptr](int p){ ptr->foo(p); };
或沒有auto
:
std::function<void(int)> func = [&ptr](int p){ ptr->foo(p); };
但是這只有在要調用的函數是固定的時才有效(即&Toto::foo
沒有動態傳遞)。 如果沒有,它仍然可以使用lambda,但你需要一個稍微不同的語法, std::bind
可能會再次具有吸引力。
使用std::bind
。
struct Toto
{
void foo( int param )
{
std::cout << "foo: " << param << std::endl;
}
};
int main() {
std::shared_ptr<Toto> ptr = std::make_shared<Toto>();
std::function< void(int) > func( std::bind( &Toto::foo,
std::bind( [ptr] () { return ptr.get(); } ),
std::placeholders::_1
) );
func( 1 );
}
編輯:帶有lambda表達式的內部bind
實際上是不必要的,但我將這里留下來作為更高級用法的說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.