#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/