Kedriik
Kedriik

Reputation: 331

Aggregated template specialisation between convertible types

Consider these template classes:

template <typename T>
class A{
  T m_t;
public:
  A(T t):m_t(t){};
};

template <typename T, typename D>
class B{
  A<D> m_a;
  T m_t;
public:
  B(T t, A<D> a):m_t(t),m_a(a){};
};

This will of course work: A<int> a{1}; .

This will also work because implicit conversion: A<int> a{'e'};

But this will not :

A<char> a{'e'}
B<int,int> b(1,a)

Is there any workaround this? I would expect implicit conversion between char and int when instantiating B class.

Upvotes: 0

Views: 55

Answers (1)

Daniel Langr
Daniel Langr

Reputation: 23497

A<char> and A<int> are two completely independent classes. But you can always add a corresponding converting constructor into the A template:

template <typename U>
A(A<U> a) : m_t(a.m_t) { }

template <typename U> friend class A;

Live demo: https://godbolt.org/z/xejPz5KM9

Note that you need to provide access to the private member m_t to all instances of A by that friend declaration. Otherwise, A<U> won't be generally able to access A<T>.m_t.

Upvotes: 1

Related Questions