【问题标题】:Can the equivalent of an operator bool cast be provided outside of a class definition somehow?是否可以在类定义之外以某种方式提供相当于运算符 bool 的类型转换?
【发布时间】:2015-07-12 17:10:39
【问题描述】:

我有一些模板化的 C++-03 代码,其中包含一个 sn-p,我想编写如下代码:

template <typeName optType>
std::string
example(optType &origVal)
{
  return bool(origVal) ? "enabled" : "disabled";
}

但是,没有为struct linger 定义optType::operator bool(),我不能添加一个,因为struct 不是我的。因此,现在,我把它写成这样:

template <typename optType>
bool
castBool(const optType &value)
{
  return bool(value);
}

template <>
bool
castBool<struct linger>(const struct linger &value)
{
  return bool(value.l_onoff);
}

template <typeName optType>
std::string
example(optType &origVal)
{
  return castBool(origVal) ? "enabled" : "disabled";
}

但是,我想知道是否有更简洁的方法可以做到这一点?比如我可以在一个类之外定义一个静态的operator==(),比如这样:

bool
operator==(const struct linger &lhs, const struct linger &rhs)
{
  return lhs.l_onoff == rhs.l_onoff && lhs.l_linger == rhs.l_linger;
}

那么也许有一些语法可以告诉编译器如何将结构体(例如此处的struct linger)提升为布尔值?

【问题讨论】:

  • operator bool() 只能作为成员实现,不能独立实现。您现有的模板专业化就是解决方案。

标签: c++ templates casting c++03 typecast-operator


【解决方案1】:

您可以在命名空间中提供一些默认版本:

namespace detail {
    template <typename T>
    bool to_bool(const T& val) { return static_cast<bool>(val); }
}

template <typename T>
bool conv_bool(const T& val) {
    using namespace detail;
    return to_bool(val);
}

然后借助 ADL 的魔力,您只需在所需类的命名空间中提供 to_bool 的一个版本:

namespace whatever {
    struct linger { ... };

    bool to_bool(const linger& value) {
        return value.l_onoff;
    }
}

然后在任何地方都使用conv_bool

template <typeName optType>
std::string
example(optType &origVal)
{
  return conv_bool(origVal) ? "enabled" : "disabled";
}

如果您提供了自己的 to_bool() 函数,那将是首选。否则,将调用默认的,它将尝试执行operator bool 或类似的操作。无需处理模板问题。

【讨论】:

    【解决方案2】:

    由于operator bool 只能是一种方法,而不是独立函数,我认为一种解决方案是从您要转换为bool 的派生类生成派生类,并在那里只实现您的运算符。除非我们正在谈论的课程是final,否则这将起作用。

    class Boolable : public optType{
    public:
        using optType::optType;
        operator bool() const{
            //your code her
        }
    };
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多