正如其他答案表明它不符合標準。
您沒有顯示預期的用法,因此有點難以弄清楚究竟是什麼,但您可以自己實現代碼(見下文),可以通過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
你問:「可以這樣不違反現行標準的字母執行」,或「可以這樣從技術的角度來實現,忽視了標準說什麼是允許的?」 – 2009-10-29 02:27:18
我都猜到了。在這種情況下,問題是:它的工作原理是什麼? – 2009-10-29 02:28:55
Duplicate:http://stackoverflow.com/questions/257288/possible-for-c-template-to-check-for-a-functions-existence – 2009-10-29 05:37:59