c++ - 我可以为 operator<< 模板运算符重载吗

标签 c++

我有这两个重载的 operator<< 函数。我可以使用模板系统将这些压缩为 1 个函数吗?

std::ostream& operator<<(std::ostream& os, const std::vector<glm::vec3>& vertices){
  for (auto i = vertices.begin(); i != vertices.end(); ++i){
    os << glm::to_string(*i) << '\n';
  }

  return os;
}

std::ostream& operator<<(std::ostream& os, const std::vector<glm::ivec3>& vertices){
  for (auto i = vertices.begin(); i != vertices.end(); ++i){
    os << glm::to_string(*i) << '\n';
  }

  return os;
}

最佳答案

是的,您可以使用函数模板std::enable_if为了有一个功能同时适用于 glm::vec3glm::ivec3 :

template <typename T>
auto operator<<(std::ostream& os, const std::vector<T>& vertices)
    -> std::enable_if_t<
            std::is_same<T, glm::vec3>::value || std::is_same<T, glm::ivec3>::value,
            std::ostream&>
{
  for (auto i = vertices.begin(); i != vertices.end(); ++i){
    os << glm::to_string(*i) << '\n';
  }

  return os;
}

live wandbox example


如果您想改为支持glm::to_string 一起使用的所有类型,您可以使用表达式 SFINAE:

template <typename T>
auto operator<<(std::ostream& os, const std::vector<T>& vertices)
    -> decltype(glm::to_string(std::declval<T>()), std::declval<std::ostream&>())
{ 
    // ... as before
}

live wandbox example

关于c++ - 我可以为 operator<< 模板运算符重载吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43309794/

相关文章:

c++ - 当您声明一个 friend 然后在类中定义它时,这意味着什么?

c++ - 在 C++ 中重置 ifstream 对象的文件结束状态

c++ - QList + QVariant + dbus,有什么区别?

c++ - 错误 : variable "cannot be implicitly captured because no default capture mode has been specified"

C++ 哈希表使用链接,删除方法

c++ - StreamTracer中的VTK访问ReasonForTermination数组

c++ - 在 C++ 中从输入函数获取参数类型的模板函数出错?

c++ - strftime - 将周数 ISO8601 转换为公历标准 C++

c++ - Hook kernel32.dll 函数使我的程序无法运行

c++ - KeyRelease 事件从未发送