Topic: Why std::function have not provided methods to assign from
Author: Johannes Schaub <schaub.johannes@googlemail.com>
Date: Mon, 12 Dec 2011 17:47:23 -0800 (PST)
Raw View
jinhao wrote:
> Refer to the definition of std::function.
>
> template<class R, class... ArgTypes>
> class function<R(ArgTypes...)> {
> public:
> //...
> function& operator=(const function&);
> function& operator=(function&&);
> function& operator=(nullptr_t);
> template<class F> function& operator=(F&&);
> template<class F> function& operator=(reference_wrapper<F>) noexcept;
>
> template<class F, class A> void assign(F&&, const A&);
> //...
> };
>
> There is a problem.
>
> void foo();
> void foo(int);
>
> std::function<void()> fn;
> fn = foo; //Error! 'void foo()'? or 'void foo(int)'?
>
> Why not provide a method for std::function to fix the problem? like this.
>
> function& operator=(R(ArgTypes...));
>
std::function<> is not specifically for storing function pointer function
objects, but is a generic wrapper that is able to store any function object
(and then some more like member function pointers) provided they are
compatible with its call signature. So since the set of possible function
objects is not known, the class accepts *any* initializer in its operator=,
then possibly failing inside its code for those that are incompatible. So it
accepts both "foo"'s, hence the ambiguity.
Apparently some implementation do what you ask for, and prevent
convertibility from incompatible function object types. See
http://stackoverflow.com/a/6194623/34509 .
--
[ comp.std.c++ is moderated. To submit articles, try posting with your ]
[ newsreader. If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]