代码之家  ›  专栏  ›  技术社区  ›  elmt

在具有不同返回类型的重载运算符上启用\u if

  •  2
  • elmt  · 技术社区  · 14 年前

    在这里,我尝试同时做三件事:使用模板重载赋值运算符、限制类型(使用boost::enable\ if)以及使用特定的返回类型。

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

    根据boost的说法 enable_if (第3节,bullet pt 1),我必须使用enable\u if作为返回类型,因为我重载了一个只能接受一个参数的运算符。但是,我希望返回类型为字符串,因此它不一定与模板参数的类型相同。

    我想使用enable\如果只是因为我想它只是跳过模板,如果它不是一个有效的类型(而不是抛出一个错误)。

    有人知道如何做到这一点吗?

    1 回复  |  直到 14 年前
        1
  •  3
  •   user405725 user405725    14 年前
    #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.
    }