lundi 2 mai 2016

Automatic type conversion for templates with const/non-const pointer types

Is it possible to provide an automatic conversion for a template class instantiated with const and non-const pointer types?

Specifically, consider the following:

template <typename T>
class A { 
public:
    operator A<const T>()
    {   
        return A<T>();
    }   
};

int main()
{
    A<const int> a1; 
    A<int> a2; 
    // Works fine; invokes operator A<const T>()
    a1 = a2; 

    A<const int*> a3; 
    A<int*> a4; 
    // Fails to compile: no viable overloaded '='
    a3 = a4; 

    return 0;
}

Is it possible to provide an explicit conversion for types with pointer template arguments? What would this look like in the definition of A?

As a bonus/background question, why does the above work for non-pointer template arguments, but not for pointer template arguments?

Aucun commentaire:

Enregistrer un commentaire