开发者

enable_if on overloaded operator with different return type

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 specifi开发者_JAVA技巧c 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?


#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.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜