I am trying to understand how the cast operator works with templates.
Consider the following code:
#include <iostream>
using namespace std;
struct S {
int v;
};
class A {
public:
A(void* ptr) : ptr(ptr) {}
void* ptr;
template<typename T>
const T& as() const {
return *static_cast<T*>(ptr);
}
template<typename T>
operator const T&() const {
return as<T>();
}
};
int main() {
S test;
test.v = 123;
A a(&test);
S s = a.as<S>();
S s2 = a; // error here
const S& s3 = a;
cout << s.v << endl;
cout << s2.v << endl;
cout << s3.v << endl;
return 0;
}
gcc gives me the following compile error:
conversion from ‘A’ to non-scalar type ‘S’ requested
I am aware, that I can fix the problem by adding another "operator T() const" but why can't the compiler figure out the right conversion in this case?
Strangely clang does not complain and compiles just fine.
(tested with gcc4.7, gcc4.8 and clang3.2)