正如其他答案表明它不符合标准。
您没有显示预期的用法,因此很难弄清楚您到底在追求什么,但您可以自己实现代码(见下文),可以使用 SFINAE 进行更多改进,以避免为每个特定类创建转换模板:
#include <iostream>
#include <sstream>
using namespace std;
struct A
{
int x;
A() : x(0) {}
};
istream& operator>>(istream& in, A& a)
{
in >> a.x;
return in;
}
ostream& operator<<(ostream& on, A& a) { return on << "A: " << a.x; }
struct B
{
int x;
B(istream& in) : x(0) { in >> x; }
};
ostream& operator<<(ostream& on, B& b) { return on << "B: " << b.x; }
struct C
{
int x;
C() : x(0) {}
static C OfStreamX(istream& in)
{
C c;
in >> c.x;
return c;
}
};
ostream& operator<<(ostream& on, C& c) { return on << "C: " << c.x; }
template <typename T> T Read(istream& in);
template <> A Read(istream& in)
{
A a;
in >> a;
return a;
}
template <> B Read(istream& in) { return B(in); }
template <> C Read(istream& in) { return C::OfStreamX(in); }
int main()
{
string data("23 45 67");
istringstream in(data);
A a = Read<A>(in);
cout << a << endl;
B b = Read<B>(in);
cout << b << endl;
C c = Read<C>(in);
cout << c << endl;
}
输出:
A: 23
B: 45
C: 67