我正在尝试为我创建的模板化堆栈类(作为编程分配)重载输出流运算符(<<)。我正在使用向堆栈类声明友元运算符<< 函数的正常范例。我遵循了 Prata 的“将模板友元函数绑定到模板类”的示例(C++ 入门加)。代码编译并执行,但没有给出预期的结果,因为模板化的 operator<< 函数试图重载 main 中输出流运算符的每次出现,而我只希望它重载 Stack 类的输出流运算符. 所以我认为我需要专门化重载的 operator<< 函数。
我构建了一个更简单的代码示例来演示这个问题。请注意,在示例中,我使用了一个名为“oper()”的函数,而不是使用重载的 operator<<。代码如下(也附上),问题是 oper() 适用于 Bigger 类(我想要)和 BIG 类(我不想要)。你能告诉我如何专门化模板化的 oper() 函数吗?
// Compiler: gcc
// Purpose: test templates. test bound template friend fns.
#include <iostream>
using namespace std;
// declare template function
template <typename T> std::ostream & oper (std::ostream &os, const T &);
template <typename T> class Bigger {
T value;
public:
Bigger(T init) {value = init;}
// declare bound template friend functions
friend std::ostream &oper<> (std::ostream &os, const Bigger<T> &);
};
class Bad { // but oper() can work with this class too!
int i;
public:
int value;
Bad(): i(1),value(2) {};
};
// define full template functions
// want to specialize this function so that it only works with class Bigger!
template <typename T> std::ostream &oper (std::ostream &os, const T & big) {
os << big.value;
return os;
}
int main (int argc, char * argv[]) {
Bigger <float> bf {3.1};
// this is desired behavior. oper() acts as a friend to Bigger.
cout << "oper bf: "; oper(cout,bf); cout<<endl;
Bad bad;
// this is undesired behavior. template is too loose allowing oper to work for Bad!!!
cout << "oper bad: ";oper(cout,bad);cout<<endl;
return 0;
}