Как в C++ сделать шаблонный абстрактный базовый класс ковариантным с его параметром шаблона?C++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Гость
 Как в C++ сделать шаблонный абстрактный базовый класс ковариантным с его параметром шаблона?

Сообщение Гость »


Я знаю это

Код: Выделить всё

std::shared_ptr
et al emulate covariance by having templated constructors.
But let's say I have an abstract base class that's a simple accessor:

Код: Выделить всё

template 
class Reader {
public:
virtual const T& Get() const = 0;
};
Then if I have a Base and Derived class (it doesn't matter what they do):

Код: Выделить всё

class Base {};
class Derived : public Base {};
It should be safe to receive a

Код: Выделить всё

std::unique_ptr
and pass it around as a . I think this should work:

Код: Выделить всё

void Frobnicate(const Reader& reader) {}

void Run() {
std::unique_ptr reader = GetReaderSomehow();
Frobnicate(*reader);
}
But if you do this you'll get an error about and not being convertible (since, fair enough, they don't inherit from one another):

Код: Выделить всё

:17:6: note: candidate function not viable: no known conversion from 'Reader' to 'const Reader' for 1st argument
17 | void Frobnicate(const Reader& reader) {}
Since is abstract, I can't just add a converting constructor to it because it will try to create an instance of Reader behind the scenes to pass as the const reference. Similarly if I try to take a

Код: Выделить всё

std::unique_ptr&
as the argument to Frobnicate, the non-convertibility makes the unique pointers non-convertible.
So, how can I do this?


Источник: https://stackoverflow.com/questions/780 ... ts-templat
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C++»