Default argument values with boost::function

Hi, Is there any way to set default argument values with Boost::Function? On VS2008 SP1 I tried: boost::function< void( unsigned i = 1 ) > increment; But this didn't work. Code such as increment( 1 ); compiles OK but if you try doing increment(); the following compiler error is triggered: error C2064: term does not evaluate to a function taking 0 arguments class does not define an 'operator()' or a user defined conversion operator to a pointer-to-function or reference-to-function that takes appropriate number of arguments Thanks, Artyom

Artyom <sneg.vx <at> googlemail.com> writes:
Hi,
Is there any way to set default argument values with Boost::Function? On VS2008 SP1 I tried:
boost::function< void( unsigned i = 1 ) > increment;
I do not think you can do it, but you can bind the value when you create the instance. Gennadiy

On Thu, Apr 30, 2009 at 12:26 PM, Gennadiy Rozental <rogeeff@gmail.com> wrote:
Artyom <sneg.vx <at> googlemail.com> writes:
Hi,
Is there any way to set default argument values with Boost::Function? On VS2008 SP1 I tried:
boost::function< void( unsigned i = 1 ) > increment;
I do not think you can do it, but you can bind the value when you create the instance.
For note, the reason this cannot be done is because C++ function types do not include overload information. Overloads are syntactic 'prettiness' handled by the compiler so if you have a function like this void myFunc(float f, int i=3); and you call it like myFunc(3.14);, it replaces that call with myFunc(3.14, 3);. Hence, it is a callsite change, not type information, and boost/std::Function only builds based on the function type. However, you can have things selectively pass variables as necessary as someone said in the most recent post.

Artyom wrote:
Is there any way to set default argument values with Boost::Function? On VS2008 SP1 I tried:
boost::function< void( unsigned i = 1 ) > increment;
But this didn't work.
I don't think this is possible with boost::function. That reminds me Boost.Overload, which was discussed some time ago on the developers mailing list. There's something in the sandbox: https://svn.boost.org/trac/boost/browser/sandbox/overload/trunk/libs/ove rload but I'm not aware of its status. A quick and dirty alternative may be something like: namespace bft = boost::function_types; namespace bmpl = boost::mpl; template< typename FuncT, typename bmpl::at<bft::parameter_types<int(int)>, bmpl::int_<0>
::type DefaultArg
struct UnaryFuncWithDefault { typedef typename bft::result_type<FuncT>::type ResultType; typedef typename bmpl::at<bft::parameter_types<int(int)>, bmpl::int_<0> >::type ArgType; UnaryFuncWithDefault(const boost::function<FuncT>& Func) : m_Func(Func){} ResultType operator()(){return m_Func(DefaultArg);} ResultType operator()(ArgType Arg){return m_Func(Arg);} boost::function<FuncT> m_Func; };
participants (5)
-
Artyom
-
Eric MALENFANT
-
Gennadiy Rozental
-
Noah Roberts
-
OvermindDL1