【问题标题】:Standard stream output for template classes模板类的标准流输出
【发布时间】:2013-02-16 22:23:55
【问题描述】:

要将对象写入命令行(或其他输出流),可以重载<< 运算符。但是有没有可能为模板实现这一点? 假设我有以下内容:

template <typename identifier>
class SomeTemplate {
public:
  SomeTemplate();
  ~SomeTemplate();
  void addElement(identifier id, unsigned int elem);
  unsigend int getElement(identifier id);
private:
  std::map<identifier, unsigned int> data_map_;
};

当我现在专注于课程时,例如std::tuple&lt;unsigned int, unsigned int, unsigned int&gt; 类型的标识符函数getElement(identifier id) 应该执行一致性检查并向std::cout 写入警告,以防data_map_ 中不存在请求的元素。 简单地将 id 传递给 cout 是行不通的,因为用于特化的类型可能没有重载的 &lt;&lt; 运算符。 还有其他可能实现这一目标吗?也许标识符必须实现一个纯虚拟类,该类强制所有标识符重载&lt;&lt; 运算符。但这可能吗?

感谢您的帮助。

问候

【问题讨论】:

  • 可以简单地执行cout &lt;&lt; id,因为在所有没有适当重载的情况下都会出现编译器错误。

标签: c++ templates generics operator-overloading


【解决方案1】:

通常的做法是简单地声明拥有流输出运算符是identifier 类型的先决条件。与使用纯虚拟方法打印的基类相比,这肯定更符合使用模板进行通用 C++ 编程的精神。

如果必须,如果没有特定类型的流输出运算符,也许可以使用 SFINAE 打印简单的“不可用”消息。

【讨论】:

    【解决方案2】:

    您的第一个问题“是否有可能为模板[重载运算符

    template <typename identifier>
    std::ostream& operator<<(std::ostream& out, SomeTemplate<identifier> const& rhs);
    

    该声明的定义可以正常工作。

    但是,您真正要问的是,我可以直播std::tuple 吗?答案似乎是否定的。你当然可以为它写一个本地的operator&lt;&lt;,但不要暴露得太广。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多