C++ 是否可以不继承boost::operators,但仍然使用它?
根据-boost::操作符的正确用法是从中派生:C++ 是否可以不继承boost::operators,但仍然使用它?,c++,templates,inheritance,boost,operators,C++,Templates,Inheritance,Boost,Operators,根据-boost::操作符的正确用法是从中派生: class A : boost::operators<A> { public: bool operator < (const A&) const { return false; } }; 最后,less\u than\u compariable1是一个boost::operators基类 问题: 但是添加这样的继承并不总是方便的。例如,此继承意味着我必须向某些结构添加构造函数,否则所有旧代码(如A{1}停止编译
class A : boost::operators<A>
{
public:
bool operator < (const A&) const { return false; }
};
最后,less\u than\u compariable1
是一个boost::operators
基类
问题:
但是添加这样的继承并不总是方便的。例如,此继承意味着我必须向某些结构添加构造函数,否则所有旧代码(如A{1}
停止编译:
struct A : boost::operators<A>
{
A() = default;
A(int a, int b = 0) : a(a), b(b) {}
int a;
int b;
};
bool operator < (const A&, const A&);
其他方法似乎都不起作用,例如,这种方法不起作用:
struct A
{
GtOperator<A> dummy;
bool operator < (const A&) const
{
return false;
}
};
结构A
{
GT操作员假人;
布尔运算符<(常数A&)常数
{
返回false;
}
};
是否可以不继承自boost::operators
,但仍然使用它
基本上没有。它的目的是继承自。它工作的原因是依赖于参数的查找只会在相关类([basic.lookup.argdep]/4)中查找友元函数和函数模板,这些类将成为A
和A
的基类。如果boost::operators取得成果,然后等待几年才能使用它
是否可以不继承自boost::operators
,但仍然使用它
基本上没有。它的目的是继承自。它工作的原因是依赖于参数的查找只会在相关类([basic.lookup.argdep]/4)中查找友元函数和函数模板,这些类将成为A
和A
的基类。如果boost::operators取得成果,然后等待几年才能使用它 或者手工写出来,或者写一个预处理器宏。(只有六个操作符,你无论如何都必须编写操作符>
。编写操作符==
通常也很有用。)@MartinBonnerboost::operators
提供的远不止这三个操作符。如果可能的话,我只是想知道如何使用它而不使用继承。或者知道为什么继承是needed@jaggedSpireboost::operators中没有对子类的强制转换。只有less\u than\u compariable1
中的朋友操作符像这样-没有向下广播。这就是为什么我要问为什么这里需要继承?或者手工写出来,或者写一个预处理器宏。(只有六个操作符,你无论如何都必须编写操作符>
。编写操作符==
通常也很有用。)@MartinBonnerboost::operators
提供的远不止这三个操作符。如果可能的话,我只是想知道如何使用它而不使用继承。或者知道为什么继承是needed@jaggedSpireboost::operators中没有对子类的强制转换。只有less\u than\u compariable1
中的朋友操作符像这样-没有向下广播。这就是为什么我要问为什么这里需要继承?我怀疑我得到了这样的答案。但我仍然不知道为什么这里需要继承?为什么这样的构造不起作用struct A{booloperator@PiotrNycz添加了这个解释。好的,我在你的回答中发现了这个wiki:and。所以答案是ADL只适用于作为基类的朋友注入的函数-这就是诀窍。我怀疑我得到了这样的答案。但是我仍然不知道为什么这里需要继承?为什么这样的构造不起作用struct A{booloperator@PiotrNycz添加了这个解释。好的,我在这个wiki上找到了与你的答案平行的答案:和。所以答案是ADL只对作为基类的朋友注入的函数有效-这就是诀窍。
template <typename A>
struct GtOperator
{
friend bool operator > (const A& l, const A& r)
{
return r < l;
}
};
struct A : private GtOperator<A>
{
bool operator < (const A&) const
{
return false;
}
};
int main() {
if (A{} > A{})
{
return -1;
}
}
struct A
{
GtOperator<A> dummy;
bool operator < (const A&) const
{
return false;
}
};
#define LESS_THAN_COMPARABLE(T) \
friend bool operator>(const T& x, const T& y) { return y < x; } \
friend bool operator<=(const T& x, const T& y) { return !static_cast<bool>(y < x); } \
friend bool operator>=(const T& x, const T& y) { return !static_cast<bool>(x < y); }
class A
{
public:
bool operator < (const A&) const { return false; }
LESS_THAN_COMPARABLE(A)
};