开发者

How do I create overloaded operators for boost pointers in C++?

From this post I see that you can't overload operators for pointers: C++: Operator overloading of < for pointers to objects

But is there any way I could overload operators for boost pointers? For example:

  boost::shared_ptr<ClassB> operator||(boost::shared_ptr<ClassA> lhs, boost::shared_ptr<ClassA> rhs) {
    boost::shared_ptr<ClassB> returnVal = CreateClassBSharedPtr(lhs, rhs);
    return returnVal;
  }

When attempting this, I get an ambiguous overload error (it conflicted with the built in operator||(bool, bool)). Any ideas to get around this?

Edit: Adding some more details below as to why I'd like to do this.

I'll try to explain what I'm attempting as best I can. What I'd like to do is make a "validator" object for maps that can check if certain properties hold. For example:

boost::shared_ptr<MyValidator> my_validator = IsEmpty("key name 1") && IsNotEmpty("key name 2") || HasNElements("key name 3", num)

Later, to validate a map:

if(my_validator.validate(some_map)) { ... }

I think I开发者_运维知识库'm stuck with using pointers because I can't use pass by value (since I'm making use of polymorphism) and I can't use pass by const reference (since there would be temporary object created by nesting operators that would not exist later when trying to validate).

Edit: Added a new question specific to my problem here: Implementation suggestions for creating an expression later used to evaluate the contents of a map in c++?


You certainly can:

#include "boost/shared_ptr.hpp"

template <class A>
bool operator||(boost::shared_ptr<A> lhs, boost::shared_ptr<A> rhs) {
    return true;
}

int main() {
    boost::shared_ptr <int> a, b;
    bool x = a || b;
}

Whether you can do what you are doing in your example, I don't know, as I'm not sure what you are trying to do!


Your approach should work, at least it works for me.

However, you will always run into the problems with ambiguous overloads when trying some user-defined conversions on rhs and lhs.


Operator|| must always return a bool, so you can't (and for the sake of the sanity of your co-workers, shouldn't) do that. I suggest you use a regular function and give it a name that reflects what you are trying to do. GetValidatedPtr() or something simlar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜