我有这两个重载的 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::vec3
和 glm::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;
}
如果您想改为支持与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
}
关于c++ - 我可以为 operator<< 模板运算符重载吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43309794/