简体   繁体   中英

Using function as operator overload in c++

I have to write a program working in general as a buffer. I created a class with some methods like AddToBuffer with overloads for char* , int , string , another instance of class etc. My task is also to create some operator overloads. So I came up with an idea to use + operator for adding to buffer, working same as AddToBuffer . Do I really have to create overloads for all parameters or can maybe 'alias' operator+ to AddToBuffer . Or maybe I should change all AddToBuffer to operator+ ?

Thanks in advance.

I expect you could do a template something like:

   class someclass
   {
     ...
     template<typename T>
     someclass operator+(T a)
     {
         return AddToBuffer(a); 
     }
     ...
   }

Since you didn't explain exactly how AddToBuffer works, it's hard to say exactly what to call to make, etc

You can use function template http://en.cppreference.com/w/cpp/language/function_template . Like this:

#include <iostream>
#include <string>

class MyBuffer
{
public:
  void AddToBuffer (const std::string& str) {
  }

  void AddToBuffer (const char* str) {
  }

  void AddToBuffer (int i) {
  }

  template<typename T>
  MyBuffer& operator+= (const T& str) {
    this->AddToBuffer (str);
    return (*this);
  }
};

int main (int argc, char *argv[])
{
  MyBuffer buffer;

  buffer += std::string("abcd");
  buffer += "abcd";
  buffer += 1;

  return(0);
}

Since others already answered the question (I think), I'll just add a few lines of personal experience:

Using operator overloads is cool. Using template classes is cool. Using polymorphism is waaaaaay cool. However, cooler doesn't make your code better; nor does shorter. There's a reason why you have string.operator+ but not queue.operator+. Operators are meant ONLY for times when you're doing something related to an operator. Adding stuff to a buffer isn't one of them. I'll give you an example. Compare this:

Stack b;
int i;
while ((i = --b) > 0)
    b--;
b += i * 2;

to this:

Stack b;
int i;
while ((i = b.Peek()) > 0)
    b.Pop();
b.Push(i * 2);

See the difference? Sure, it's cooler to override some operators and write code that no one can read, but code (at least useful code) isn't meant to be cool. It's meant to work, to be reusable, to be readable, etc. C++ is a very dangerous language in that it allows you to do virtually anything, and lets you get away with it. If you're not careful what you do, you might end up knee-deep in trouble, trying to get something to work that would have worked so much better had you just written it some other way. I've been there. Don't make the same mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM