C — Извлечь параметр шаблона из производного класса

#c #templates #generic-programming

#c #шаблоны #универсальный-программирование

Вопрос:

Могу ли я извлечь параметр типа из производного класса? Что-то вроде этого:

 template<typename T>
class A {
...
};

struct TheType {};

class B : public A<TheType> {
...
};

template<typename DerivedClass>
class C {
  // If DerivedClass is B
  // Can I extract the type parameter T of B:A<T> inside of C?
  DerivedClass elem;
};
  

Ответ №1:

Вы можете добавить type в A :

 template<typename T>
class A {
protected:
    using type = T;
    ...
};
  

Затем вы можете использовать typename DerivedClass::type в C .

Комментарии:

1. Это using type = T; .

Ответ №2:

Без изменения A вы могли бы сделать:

 // declaration only
template <typename T> T ATemplateTypeImpl(const A<T>amp;);

template <typename T>
using ATemplateType = decltype(ATemplateTypeImpl(std::declval<T>()));


static_assert(std::is_same<TheType, ATemplateType<B>>);
  

Комментарии:

1. Без изменения 🙂 Очень приятно.