C++ 是否可以以某种方式在类定义之外提供与运算符bool cast等价的内容?
我有一些模板化的C++-03代码,其中包含一个片段,我想这样写:C++ 是否可以以某种方式在类定义之外提供与运算符bool cast等价的内容?,c++,templates,casting,c++03,typecast-operator,C++,Templates,Casting,C++03,Typecast Operator,我有一些模板化的C++-03代码,其中包含一个片段,我想这样写: template <typeName optType> std::string example(optType &origVal) { return bool(origVal) ? "enabled" : "disabled"; } bool operator==(const struct linger &lhs, const struct linger &rhs) { return
template <typeName optType>
std::string
example(optType &origVal)
{
return bool(origVal) ? "enabled" : "disabled";
}
bool
operator==(const struct linger &lhs, const struct linger &rhs)
{
return lhs.l_onoff == rhs.l_onoff && lhs.l_linger == rhs.l_linger;
}
但是,我想知道是否有一种更简洁的方法可以做到这一点?例如,我可以在类之外定义一个静态操作符==()
,如下所示:
template <typeName optType>
std::string
example(optType &origVal)
{
return bool(origVal) ? "enabled" : "disabled";
}
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);
}
然后到处使用conv\u bool
template <typeName optType>
std::string
example(optType &origVal)
{
return conv_bool(origVal) ? "enabled" : "disabled";
}
模板
字符串
示例(optType和origVal)
{
返回conv_bool(origVal)?“已启用”:“已禁用”;
}
如果您为_bool()函数提供了自己的
,那么这将成为首选。否则,将调用默认值,该值将尝试执行运算符bool
或其他等效操作。不必处理模板问题 由于操作符bool
只能是一个方法,而不是一个独立的函数,我认为解决方案之一是从您想要转换到bool
的方法生成派生类,并在那里只实现您的操作符。除非我们讨论的课程是最终的
,否则这将起作用
class Boolable : public optType{
public:
using optType::optType;
operator bool() const{
//your code her
}
};
operator bool()
只能作为成员实现,不能独立实现。您现有的模板专门化就是解决方案。我认为您的意思是“成员函数”。。。它不必是虚拟的
(像方法一样)@BenVoigt AFAIK method==成员函数。不,它们根本不是对等的。我看到了两种常见的“方法”定义——基于对象的(动态类型)调度,它只包括虚拟成员函数和基于静态的调度,它根本不必是成员。@ BeoVigt这样证明我错了,并给出了C++与C++的链接,显示了差异。