10

I'm writing a C+11 function that takes a callable as an argument, and I'd like to have that argument default to a no-op function. This is my best attempt so far:

const std::function<void()> noop= [](){};
void f( int x, int y, std::function<void()> fn= noop ) { /* ... */ }

I'm wondering whether the standard libraries provide a "noop" std function for me, or do I need to write my own as I have above? I'm also wondering if there's a way to avoid explicitly naming the "noop" function. For example:

void f( int x, int y, std::function<void()> fn= [](){} ) { /* ... */ }

won't compile (in Visual Studio 2012 Update 3), nor will:

void f( int x, int y, std::function<void()> fn= std::function<void()>([](){}) ) { /* ... */ }
4

1 に答える 1

3

標準ライブラリが "noop" std 関数を提供してくれるのか、それとも上記のように自分で書く必要があるのか​​ 疑問に思っていますか?

いいえ、デフォルトの noop 関数はありません。この場合、(noop functor オブジェクトで行ったように) 独自のものを作成する必要があります。

于 2013-07-24T19:28:26.840 に答える