So I have a std::vector<std::unique_ptr<Base>> vec
and I'm trying to sort it dynamically, given that there are logical comparisons between Derived1 to Derivedn (Derivedn always > Derivedn-1 > ... > Derived1) (say n = 10 or so) and each Derivedx has it's own different comparison with Derivedx. As an example, think 10 digit integer > 9 digit integer > 1 digit integer, but within each derived class 53 > 32 (but I'm not sorting integers).
So I can do this:
std::sort(vec.begin(), vec.end(),
[](std::unique_ptr<Base>& const a, std::unique_ptr<Base>& const b){
return *a<*b;}
And then in Base, have a function Base::operator<(const Base& b)
make comparisons if they are different Derived classes, and cast to Derivedx if they are the same with Derivedx::operator<(const Derivedx& d)
if they are the same derived.
However, I would think that there's a way that I can compare a to b automatically given the appropriate definitions in the derived classes, but I have been unable to implement it due to compile errors. I cannot get the lambda function to compare Derivedx < Derivedy dynamically.
I've tried Base::operator<(const std::unique_ptr<Base>)
and then use return *a<b
for a compiler error, saying that I used a deleted copy assignment operator (which I don't understand, where is the assignment??). An abstract virtual Base::operator<(const Base& b)
does practically the same thing I'm开发者_如何转开发 doing now with more work because I have to implement Derivedx::operator<(const Base& b)
(for each Derivedx) and then cast down to (Derivedx) if they're the same.
It may just be better that I compare everything in the base class rather than implementing n^2 comparisons in (n comparisons in n derived classes) though. But I do want to see if I can keep things "object oriented".
Any thoughts on the design issue?
Thanks.Take a look at Chapter 31, Making functions virtual with respect to more than one object in Scott Meyers, More Effective C++.
Also, try googling on the phrases double dispatch and multiple dispatch.
Hmm... I probably would have used overriding the operator<
with the set of relevant variants. This would then be independent from any class hierarchy. But maybe this is not what you want.
精彩评论