Reputation: 3727
I was wondering what's wrong with the following code:
template<typename T, typename U = T>
operator U()
{
return U();
}
It fails with error: no matching function for call to 'Test1::Test1(Test&)'
, whereas the conversion on the following code succeeds:
template<typename T>
operator T()
{
return T();
}
The complete code:
class Test
{
public:
template<typename T, typename U = T>
operator U()
{
return U();
}
};
class Test1{};
int main() {
Test t;
Test1 t1 = (Test1)t;
return 0;
}
class Test
{
public:
template<typename T>
operator T()
{
return T();
}
};
class Test1{};
int main() {
Test t;
Test1 t1 = (Test1)t;
return 0;
}
Upvotes: 0
Views: 41
Reputation: 92231
You are making it too hard for the compiler with this
template<typename T, typename U = T>
operator U()
{
return U();
}
The code says "U is the same type as T". And the compiler asks "And what is T?". T
isn't used anywhere in your code, so the compiler cannot deduce it.
typename U = T
only works one way, to define U
when T
is known.
Upvotes: 2