【发布时间】: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