2

I am trying to basically do 3 things at once here: overload the assignment operator using a template, restrict the types (using boost::enable_if), and having a specific return type.

Take this as an example:

template <class T>
std::string operator =(T t) {  return "some string"; }

Now, according to boost enable_if (sec 3, bullet pt 1), I would have to use the enable_if as the return type since I'm overloading an operator which can only take one argument. However, I would like the return type to b a string and so it may not necessarily be the same type as the template argument.

I would like to use enable_if simply because I want it to just skip over the template if it is not a valid type (not throw an error).

Anyone have an idea on how to accomplish this?

1
  • Pass the type you actually want (in this case, std::string) into enable_if.
    – alicederyn
    Sep 2, 2010 at 12:40

1 Answer 1

3
#include <iostream>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/contains.hpp>

class FooBar
{
public:
    FooBar () {}
    ~FooBar () {}

    template <typename T>
    typename boost::enable_if <
        typename boost::mpl::contains <
            boost::mpl::vector<std::string, int>, T>::type,
            std::string>::type
    operator = (T v)
    {
        return "some string";
    }
};

int
main ()
{
    FooBar bar;
    bar = 1;
    bar = std::string ("foo");
    // bar = "bar"; // This will give a compilation error because we have enabled
                    // our operator only for std::string and int types.
}
1
  • Wonderful, this is a great example of how powerful the boost libraries are. Thank you.
    – elmt
    Sep 2, 2010 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.