user3691884
user3691884

Reputation: 11

C++ operator overloading issue: expected initializer before '<<' token

I am trying to overload the insertion operator '<<' to simplify some syntax required to use a specific piece of software. That software implements a hash object which holds a variety of types of data, so type checking cannot be done at compile-time because the type of the RHS of a given expression is not known until run-time. This hash is very similar in spirit to Boost Property Trees.

I am trying to write this as a template function to extract data from the hash. This works just fine as long as the receiving variable already exists (is initialized). It fails to compile if this is used during variable initialization.

So, this compiles and works fine.

int value;
value << data;

But this does not compile at all.

int value << data;

The real code is quite large and complex so I have written the following simplified program to exhibit the same behaviors.

I am using gcc version 4.3.4. A different compiler is not an option.

Any and all help is appreciated.

#include <iostream>

/**
  * Simple class to use with the templates.
  */
class Data
  {
public:
    Data ()
      {
        m_value = 0;
      }
    Data (int val)
      {
        m_value = val;
      }
    ~Data ()
      {
      }
    int value ()
      {
        return (m_value);
      }
    int value (int val)
      {
        m_value = val;
        return (value ());
      }
private:
    int m_value;
  };

/**
  * Assign data from RHS to LHS.
  */
template <class T>
void operator<< (T &data, Data &node)
  {
    data = node.value ();
  }

/**
  * Simple test program.
  */
int main (int argc, char *argv[])
  {
    // initialize the data
    Data data (123);
    std::cout << data.value () << std::endl;

    // extract the data and assign to integer AFTER initialization
    int value;
    value << data;
    std::cout << value << std::endl;

    // extract the data and assign to integer DURING initialization
    // *** problem is here ***
    int other << data; // <-- this fails to compile with...
    // expected initializer before '<<' token
    std::cout << other << std::endl;

    return (0);
  }

Upvotes: 1

Views: 1780

Answers (2)

quantdev
quantdev

Reputation: 23793

int value << data; is not valid C++.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234655

int value << data; does not make grammatical sense.

Think of << as being like any other operator, rather like +=. Yes, << is overloaded but it still has to obey the same semantics as its natural incarnation as a bitwise shift.

int value += 3; for example, makes no sense either.

Upvotes: 3

Related Questions