2

Hey guys can someone help me out?

My problem is that I don't know how to use templates with operators correctly.

This is my class:

template <typename T>
class myClass {

public:
    myClass() {}
};

template <typename T>

//create copy of object T in myClass
myClass& operator<<(const T&) {

    //how should my code look right here?

}

myClass& operator>>(T&){
     //and here ??
}

And this is my main:

#include <iostream>
#include <string>
#include <fstream>

int main(){

myClass<string> e; // create empty myClass
string someText = "testing this text blabla";
e << someText;  //input of someText in e

//test if input works correctly
string test;
e >> test; //put value of e in string test
cout << test << endl; //output test

return 0;
}
Coder95
  • 131
  • 1
  • 9
  • It is not perfectly clear what you are trying to attempt. Your `myClass` should behave just as a sort of container of an object `T`? – BiagioF Nov 28 '19 at 11:26
  • Non-member operator overloading needs *two* arguments: The object to use, and the other object or value to to something with. See e.g. [this operator overloading reference](https://en.cppreference.com/w/cpp/language/operators) for more information. And of course [get a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read, as they should explain it clearly. – Some programmer dude Nov 28 '19 at 11:27
  • If it was a `string` how would you copy it? Do that, but write `T` instead of `string`. – user253751 Nov 28 '19 at 11:33

1 Answers1

2

Just going by the code in the main function:

e << someText;  //input of someText in e

and

e >> test; //put value of e in string test

Perhaps you could do something like

template<typename T>
class myClass
{
public:
    myClass() = default;  // Defaulted default constructor

    myClass& operator<<(T const& val)
    {
        value_ = val;
        return *this;
    }

    myClass& operator>>(T& val)
    {
        val = value_;
        return *this;
    }

private:
    T value_;
};

There are two alternatives to this: Declare the operators as friend non-member functions. Or add a getter and setter pair of functions to get and set the value, then use non-member functions that uses the getter/setter functions to get and set the value.

But remember that non-member function (friend or otherwise) needs the object as the first argument. This is because for non-member operators

e >> test;

is actually translated as

operator>>(e, test);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621