不正确的模板专业化
Not correct template specialization
请告诉我我有 class Foo
,其中超载了 operator<<
。
我需要 operator<<
以不同方式处理 unsigned
类型。
为此,我试图声明一个模板专业化,但错误地。
#include <iostream>
class Foo {
public:
Foo(std::ostream& out)
: _out(out) {}
template <typename T>
Foo& operator<<(const T& s) {
_out << "[]: " << s;
return *this;
}
template <>
Foo& operator<<(const unsigned& s) {
_out << s;
return *this;
}
private:
std::ostream& _out;
};
int main() {
Foo foo(std::cout);
unsigned a = 5;
foo << "test\n"; // template
foo << a; // unsigned
}
你如何正确地做到这一点?
正如@super 正确指出的那样,在这种情况下重载更有意义。为了完整起见,这是完成模板专业化的方式:
#include <iostream>
class Foo {
public:
Foo(std::ostream& out) : _out(out) {}
template <typename T>
Foo& operator<<(const T& s) {
_out << "[]: " << s;
return *this;
}
private:
std::ostream& _out;
};
template <>
Foo& Foo::operator<<(const unsigned& s) {
_out << "[const uint&]: " << s;
return *this;
}
int main() {
Foo foo(std::cout);
unsigned a = 5;
foo << "test\n"; // template
foo << a; // specialized
}
请告诉我我有 class Foo
,其中超载了 operator<<
。
我需要 operator<<
以不同方式处理 unsigned
类型。
为此,我试图声明一个模板专业化,但错误地。
#include <iostream>
class Foo {
public:
Foo(std::ostream& out)
: _out(out) {}
template <typename T>
Foo& operator<<(const T& s) {
_out << "[]: " << s;
return *this;
}
template <>
Foo& operator<<(const unsigned& s) {
_out << s;
return *this;
}
private:
std::ostream& _out;
};
int main() {
Foo foo(std::cout);
unsigned a = 5;
foo << "test\n"; // template
foo << a; // unsigned
}
你如何正确地做到这一点?
正如@super 正确指出的那样,在这种情况下重载更有意义。为了完整起见,这是完成模板专业化的方式:
#include <iostream>
class Foo {
public:
Foo(std::ostream& out) : _out(out) {}
template <typename T>
Foo& operator<<(const T& s) {
_out << "[]: " << s;
return *this;
}
private:
std::ostream& _out;
};
template <>
Foo& Foo::operator<<(const unsigned& s) {
_out << "[const uint&]: " << s;
return *this;
}
int main() {
Foo foo(std::cout);
unsigned a = 5;
foo << "test\n"; // template
foo << a; // specialized
}