【问题标题】:enable_if on overloaded operator with different return type在具有不同返回类型的重载运算符上启用_if
【发布时间】:2010-09-01 19:33:16
【问题描述】:

我在这里尝试基本上同时做 3 件事:使用模板重载赋值运算符、限制类型(使用 boost::enable_if)以及具有特定的返回类型。

以此为例:

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

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

我想使用 enable_if 只是因为如果模板不是有效类型(不抛出错误),我希望它跳过模板。

有人知道如何实现这一点吗?

【问题讨论】:

  • 将您真正想要的类型(在本例中为 std::string)传递给 enable_if。

标签: c++ templates boost operator-overloading


【解决方案1】:
#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.
}

【讨论】:

  • 太棒了,这是一个很好的例子,说明了 boost 库的强大。谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
相关资源
最近更新 更多