C++ 运算符重载问题 : expected initializer before '<<' token

标签 c++ templates compiler-construction initializer

我正在尝试重载插入运算符“<<”以简化使用特定软件所需的一些语法。该软件实现了一个包含各种类型数据的哈希对象,因此无法在编译时进行类型检查,因为直到运行时才知道给定表达式的 RHS 类型。这个散列在本质上与 Boost Property Trees 非常相似。

我正在尝试将其编写为模板函数以从散列中提取数据。只要接收变量已经存在(已初始化),这就可以正常工作。如果在变量初始化期间使用它,则编译失败。

所以,这可以编译并正常工作。

int value;
value << data;

但这根本无法编译。

int value << data;

真正的代码非常庞大和复杂,所以我编写了以下简化程序来展示相同的行为。

我使用的是 gcc 4.3.4 版。不同的编译器不是一个选项。

感谢任何帮助。

#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);
  }

最佳答案

int value << data;没有语法意义。

想到<<就像任何其他运营商一样,而不是像 += .是的,<<已重载,但它仍然必须遵守与其自然化身相同的语义,如按位移位。

int value += 3;例如,也没有意义。

关于C++ 运算符重载问题 : expected initializer before '<<' token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23958529/

相关文章:

c++ - 从 boost unordered_map 中删除特定键

c++ - 结合 Eigen 和 CppAD

c++ - 更改 "template<...>"行中模板参数的顺序是否应该导致重复定义或歧义?

c++ - 使用 C/C++ 命名进程内部互斥体?

c++ - constexpr std::array with static_assert

c++ - 这个堆栈有什么问题?

c++ - 如何以非内联方式定义模板覆盖的功能

c++ - 编译器内存屏障和互斥量

C++ 编译。翻译阶段#1。通用字符名称

compiler-construction - 如何创建 JVM 编程语言?