Re: What's the proper way of initializing a std::function?
On 29 Apr., 21:03, DeMarcus <use_my_alias_h...@hotmail.com> wrote:
[..]
In C++0x, is lambda the most proper way to initialize a std::function
with a valid function that does nothing?
class SomeClass
{
public:
SomeClass() : fnc_([]{}) {}
private:
std::function<void()> fnc_;
};
I'm not sure whether I understand your question correctly:
Is your requirement, that std::function should have a
target?
1) If not, why is the default constructor not OK?
2) If yes, it depends on what the most reasonable
default behaviour is, and that is quite use-case-
dependent. A no-op behaviour is probably a good
initial approach (Null Object Pattern) for many.
Regarding (2) it is also relevant to think of
a user who may want to get the target of the
function (if this becomes available), e.g.
#include <functional>
#include <cassert>
class SomeClass
{
public:
SomeClass() : fnc_(empty_) {}
const std::function<void()>& fnc() const { return fnc_; }
using empty_target_type = void(*)();
static empty_target_type empty() { return empty_; }
private:
static void empty_(){};
std::function<void()> fnc_;
};
int main() {
SomeClass s;
const SomeClass::empty_target_type* ptr =
s.fnc().target<SomeClass::empty_target_type>();
assert(*ptr == SomeClass::empty());
}
is quite easy, but to realize the same thing with a
lambda closure is much harder.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]