我有一些模板化的 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/