c++ - 是否可以在类定义之外以某种方式提供相当于 operator bool cast 的东西?

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

我有一些模板化的 C++-03 代码,其中包含一个片段,我想这样写:

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 等结构提升为 bool?

最佳答案

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

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 或一些等效操作。无需处理模板问题。

关于c++ - 是否可以在类定义之外以某种方式提供相当于 operator bool cast 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31370390/

相关文章:

c++ - 返回 std::function 的类 std::bind 函数

c++ - 无法从派生类调用基模板类的构造函数

c++ - 为命名空间中的类特化方法模板

c++ - 如何使用一次广播在 MPI 中传输不同类型的 vector

c++ - 跳过循环 C++

c++ - 在 C++ 中使用通用接口(interface)实现比较

c# - 有没有办法使 .NET Cast<T> 扩展方法使用用户定义的隐式转换运算符?

c - (无符号强制转换)值和写入值之间的区别?

c++ - MFC 自动建议文本框(如 Windows“开始”->“运行”对话框)

c++ - Eclipse,如果程序崩溃则看不到输出