Search code examples
c++templatesconversion-operator

Conversion operator with default template argument


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:

https://ideone.com/yWVtgR

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;
}

https://ideone.com/XcRkTn

class Test
{
    public:
        template<typename T> 
        operator T() 
        {
            return T();
        }
};
class Test1{};

int main() {
    Test t;
    Test1 t1 = (Test1)t;

    return 0;
}

Solution

  • 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.