Boost logo

Boost Users :

Subject: Re: [Boost-users] boost::function unusable as overloadable function argument
From: Peter Soetens (peter.soetens_at_[hidden])
Date: 2009-08-27 12:41:07


On Thu, Aug 27, 2009 at 18:25, Steven Watanabe<watanabesj_at_[hidden]> wrote:
> AMDG
>
> Peter Soetens wrote:
>>
>> I had this situation in a bigger program, where a user could supply a
>> string or a function object:
>>
>> <code>
>> #include <boost/function.hpp>
>> #include <string>
>>
>> void foo1(int i, std::string a);
>> void foo1(int i, boost::function<void(void)> foo );
>>
>> int main(int argc, char** argv)
>> {
>>  //boost::function<void(void)> foo = "hello"; // this line won't compile
>>
>>  foo1( 3, "hello" ); //error: call of overloaded ‘foo1(int, const
>> char [6])’ is ambiguous
>>
>>  return 0;
>> }
>> </code>
>>
>>
>> Although constructing a boost::function from a C string is nonsense,
>> the compiler does consider it as an alternative when trying to find
>> the right foo1. Is there any work around to keep the overloads without
>> requiring the user to write
>> foo1(3, string("hello")); or is this a compiler bug (g++ (Ubuntu
>> 4.3.3-5ubuntu4) 4.3.3)?
>>
>
> You can use tag dispatching:
>
> void foo1_impl(int, std::string a, boost::mpl::true_);
> void foo1_impl(int, boost::function<void(void)>, boost::mpl::false_);
>
> template<class T>
> void foo1(int i, T t) {
>   foo1_impl(i, t, boost::is_convertible<T, std::string>());
> };

Thank you for this solution ! I'm sure it will help me at some future
point in time to resolve issues of this kind. I feel I can't however
put this in the interface of my library, It's a very much used
function by users and the interface has to be very clear, so no
template argument if only two types are accepted.

The only solution I see now is renaming the function name.

Thanks again,
Peter


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net