gpt4 book ai didi

c++ - 使用函数模板重载运算符

转载 作者:行者123 更新时间:2023-12-03 23:01:30 26 4
gpt4 key购买 nike

我的工作是重载 operator<<所以它可以打印任何对象(例如 std::vectorstd::setstd::mapstd::deque 等)
凭借我对模板的基本了解并在网上搜索,我得出了这样的结论:

template <typename T>
std::ostream& operator<<(std::ostream& stream, const std::vector<T>& v){
stream << '[';
for(const auto& element : v){
stream << element << ' ';
}
stream << ']';

return stream;
}

int main(){
std::vector<double> foo = {1.2, 2.1, 3.56};
std::set<double> roo = {1.2, 2.1, 3.56};

std::cout << foo << std::endl;
std::cout << roo << std::endl;
}
但它不会打印 std::set或任何其他对象。我试过更换 const std::vector<T>& vconst T& v但它不会编译。有关如何解决此问题的任何提示?

最佳答案

I've tried replacing const std::vector<T>& v with const T& v but it won't compile.


您可以对类型进行约束以避免与重载 operator<< 发生冲突由图书馆提供。例如。
// works on types supporting std::begin and std::end
template <typename T>
auto operator<<(std::ostream& stream, const T& v) -> decltype(std::begin(v), std::end(v), stream) {
stream << '[';
for(const auto& element : v){
stream << element << ' ';
}
stream << ']';

return stream;
}
LIVE

关于c++ - 使用函数模板重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65445554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com