dimanche 9 février 2020

Class hierarchy in templated types in C++

I am working on a simple project where there are publishers who read from one data source and construct events for subscribers to work on.

An event will have a unique ptr to the data and the subscribers will have a shared ptr to the event.

I want to have a common interface to an event so a subscriber can subscribe to an arbitrary Data publisher. But a publisher can publish only one type of Data.

#include <memory>
#include <iostream>

class Data
{

};

class ChildData : public Data
{
};

template<typename T>
class Event
{
    std::unique_ptr<T> _data;
};

void someFunc(Event<Data> event)
{
    std::cout << "hello Word" << std::endl;
}

int main()
{
    Event<ChildData> event();
    someFunc(event);
    return 0;
}

but am getting the following compiler error

/home/rory/dev/cpp_sandbox/main.cpp: In function ‘int main()’:
/home/rory/dev/cpp_sandbox/main.cpp:27:19: error: could not convert ‘event’ from ‘Event<ChildData> (*)()’ to ‘Event<Data>’
     someFunc(event);
                   ^
CMakeFiles/example.dir/build.make:62: recipe for target 'CMakeFiles/example.dir/main.cpp.o' failed
make[2]: *** [CMakeFiles/example.dir/main.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/example.dir/all' failed
make[1]: *** [CMakeFiles/example.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

Is this sort of thing possible in C++?

Aucun commentaire:

Enregistrer un commentaire