c++ - 重载 `std::ostream`运算符时,是否可以更改默认非类型模板参数?

标签 c++ c++11

#include <iostream>

struct Foo {
  template <int bias = 5>
  void print() {
    std::cout << bias << std::endl;
  }
};

template <int bias = 5>
std::ostream &operator<<(std::ostream &os, const Foo &foo) {
  return os << bias;
}

int main() {
  Foo a;
  a.print();
  a.print<>();
  a.print<1>();
  std::cout << a << std::endl;
  return 0;
}
通过显示此代码,我的意思是,尽管实现很糟,但是有一种方法可以更改默认参数5 以使用Foo a格式输出std::cout << a << std::endl并保持struct不变吗?

最佳答案

当您像运算符一样调用operator <<时,无法添加模板参数。

std:cout << a << std::endl;
但是,如果像函数一样调用operator <<,则可以添加template参数。请注意,由于返回类型为std::ostream &,因此您可以使用运算符样式语法调用更多的operator <<
operator<< <3>(std::cout, a) << std::endl;
也可以在输出operator <<之前添加更多a调用,但是看起来并不像您的原始调用那么好。
operator<< <3>(std::cout << "a=", a) << std::endl;
operator <<原始链配合使用的另一个选项是通过引入帮助器类来实现的。
template<int Bias>
struct Biased {
    Biased(Foo& foo) :_foo{ foo } {}
    Foo& _foo;
};

template<int Bias>
std::ostream& operator<<(std::ostream& os, const Biased<Bias>& biased) {
    return os << Bias;
}

std::cout << "a=" << Biased<42>(a) << std::endl;
请注意,我在_foo中添加了Biased,以便如果需要的话,operator <<Biased也可以打印_foo的内容(此处不发生此代码)。

关于c++ - 重载 `std::ostream`运算符时,是否可以更改默认非类型模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63189422/

相关文章:

c++11 - 如何使用旧的 ABI 通过 GCC 5 编译 boost?

c++ - OpenMP 并行部分的 firstprivate 中是否允许非 POD 数据类型?

c++ - 带智能指针的多态性

c++ - 具有不同模板参数的函数返回类型

c++ - 模板 'using' 声明不起作用

c++ - 我应该停止使用术语 C/C++ 吗?

c++对象输出错误信息

c++ - C++ 字符串类可以进行指针运算吗?

c++ - 如何使用 union 成员的大小计算编译时值?

c++ - 如何创建一个返回数组的函数