I have a base class.
#include <string.h>
class Channel
{
private:
std::string stdstrName;
public:
Channel() : stdstrName("CHANNEL"){ }
Channel(std::string name) : stdstrName(name){ }
void PrintName() { std::cout << stdstrName << std::endl; }
};
which is inherited by Position class.
class PositionChannel : public Channel
{
public:
std::vector<int> keyframes;
PositionChannel() : Channel("POSITION") , keyframes( { 1 , 2, 3 }) { }
};
There is a director class which has the channel clas as its data members.
#include "Channel.h"
#include <memory>
class Director
{
private:
std::vector<std::shared_ptr<Channel>> channels;
public:
void AddChannel(std::shared_ptr<Channel> chn) { channels.push_back(chn); }
void GetChannel(Channel **chn) { *chn = channels[0].get(); }
};
now when in the main function.
// Free function
template<typename T>
void GetChannel(Director *dir)
{
T *chn;
dir->GetChannel(&chn);
}
Director dir;
PositionChannel channel;
std::shared_ptr<Channel> channelPointer = std::make_shared<Channel>(channel);
dir.AddChannel(channelPointer);
GetChannel< PositionChannel>(&dir); // here i get error
this is the error message error C2664: ' cannot convert argument 1 from 'T **' to 'Channel **
if i change the templated function to a non templted function than i do not get any error.
In you GetChannel call, &chn argument is of type PositionChannel**, but the type of Director::GetChannel parameter is Channel**. These two types are not convertible; see, for example this question: Conversion of pointer-to-pointer between derived and base classes?.
I am not sure what are your intentions since the code does not make much sense as is, but you can redefine GetChannel as follows:
template<typename T>
void GetChannel(Director *dir)
{
Channel* ptr;
dir->GetChannel(&ptr);
T *chn = ptr;
}
T can be any type, you can't convert it to a Channel for any type.
There are probably ways to make it work with templates, but I feel like your problem could be more easily solved by using polymorphism with something like this :
void GetChannel(Channel* chn, Director *dir)
{
dir->GetChannel(&chn);
}
And then chn can be any type dervived from Channel.
Yes, Daniel Langr already gave the correct answer. I added a check in the template if the class is derived.
#include <type_traits>
class Channel
{
public:
virtual ~Channel() = default;
};
class PositionChannel : public Channel
{
};
struct Director{
void GetChannel(Channel **c) {}
};
template <typename T,
typename = typename std::enable_if<std::is_base_of<Channel, T>::value, T>::type>
void GetChannel(Director *dir)
{
Channel *chn;
dir->GetChannel(&chn);
T* ptr = static_cast<T*>(chn);
}
int main(void) {
Director dir;
GetChannel<PositionChannel>(&dir);
return 0;
}
Related
How can one do this, which is obviously impossible C++, in real C++?:
Type decodeUiEnum(UiEnum myEnum) { // impossible: cannot return a data type
// one switch statement to rule them all
switch(myEnum) {
case USER_SELECTED_GREYSCALE: return GreyscalePixel;
case USER_SELECTED_RGB: return RgbPixel;
...
}
}
void doSomeGraphicsMagic1(UiEnum myEnum) {
...
Foo<decodeUiEnum(myEnum)> a(...); // impossible: type not available at compile
// time
...
}
void doSomeGraphicsMagic2(UiEnum myEnum, int blah) {
...
Bar<int, decodeUiEnum(myEnum)> b(...); // impossible
...
}
and the like, so you can just add new types to the top switch statement and not have to modify the other code below it, so long as that code is suitably generic of course? As otherwise, you would need a switch statement within each function to do the necessary type mapping into the templates, which is not as much maintainable code, and lots of duplication. So more generally - if this is approaching it the wrong way, how do we fulfill that intended property of the code?
That is, what I want to do is, in a function taking an enum as parameter, instantiate a template type where the template parameter depends on the enum, without having a switch-on-enum in every function.
Yes it is actually possible.
Trick is based on partial template specification, this approach used by std::get
For example:
#include <iostream>
// specify an enumeration we will use as type index and related data types
enum class UiEnum {
GRAY_SCALE,
RGB_PIXEL
};
struct GreyscalePixel;
struct RgbPixel;
// make base template class
template<UiEnum _EV>
struct ui_enum_type {
};
// do partial type specification trick
// insert typedefs with data type we need for each enumeration value
template<>
struct ui_enum_type<UiEnum::GRAY_SCALE> {
typedef GreyscalePixel pixel_type;
};
template<>
struct ui_enum_type<UiEnum::RGB_PIXEL> {
typedef RgbPixel pixel_type;
};
// demo classes to demonstrate how trick is working at runtime
template<typename T>
struct demo_class {
};
template <>
struct demo_class<GreyscalePixel> {
demo_class()
{
std::cout << "GreyscalePixel" << std::endl;
}
};
template <>
struct demo_class<RgbPixel> {
demo_class()
{
std::cout << "RgbPixel" << std::endl;
}
};
// use swithc trick
static void swich_trick(std::size_t runtimeValue)
{
switch( static_cast<UiEnum>(runtimeValue) ) {
case UiEnum::GRAY_SCALE: {
demo_class< ui_enum_type<UiEnum::GRAY_SCALE>::pixel_type > demo1;
}
break;
case UiEnum::RGB_PIXEL: {
demo_class< ui_enum_type<UiEnum::RGB_PIXEL>::pixel_type > demo2;
}
break;
}
}
int main(int argc, const char** argv)
{
// Do runtime based on the trick, use enum instead of data type
for(std::size_t i=0; i < 2; i++) {
swich_trick(i);
}
return 0;
}
In any case my suggestion - use classic polymorphism instead of template meta-programming over complication. Most modern compilers doing de-virtualization during optimization. For example:
#include <iostream>
#include <memory>
#include <unordered_map>
enum class UiEnum {
GRAY_SCALE,
RGB_PIXEL
};
class GraphicsMagic {
GraphicsMagic(const GraphicsMagic&) = delete;
GraphicsMagic& operator=(const GraphicsMagic&) = delete;
protected:
GraphicsMagic() = default;
public:
virtual ~GraphicsMagic( ) = default;
virtual void doSome() = 0;
};
class GreyscaleGraphicsMagic final: public GraphicsMagic {
public:
GreyscaleGraphicsMagic():
GraphicsMagic()
{
}
virtual void doSome() override
{
std::cout << "GreyscalePixel" << std::endl;
}
};
class RgbGraphicsMagic final: public GraphicsMagic {
public:
RgbGraphicsMagic():
GraphicsMagic()
{
}
virtual void doSome() override
{
std::cout << "RgbPixel" << std::endl;
}
};
int main(int argc, const char** argv)
{
std::unordered_map< UiEnum, std::shared_ptr< GraphicsMagic > > handlers;
handlers.emplace(UiEnum::GRAY_SCALE, new GreyscaleGraphicsMagic() ) ;
handlers.emplace(UiEnum::RGB_PIXEL, new RgbGraphicsMagic() );
for(std::size_t i=0; i < 2; i++) {
handlers.at( static_cast<UiEnum>(i) )->doSome();
}
return 0;
}
You could use std::variant, and then have consuming code std::visit that variant.
First we want a template for "pass a type as a parameter"
template <typename T>
struct tag {
using type = T;
};
Then we define our variant and the factory for it.
using PixelType = std::variant<tag<GreyscalePixel>, tag<RgbPixel>>;
PixelType decodeUiEnum(UiEnum myEnum) {
switch(myEnum) {
case USER_SELECTED_GREYSCALE: return tag<GreyscalePixel>{};
case USER_SELECTED_RGB: return tag<RgbPixel>{};
...
}
}
Now our methods can be written as visitors over PixelType
void doSomeGraphicsMagic1(UiEnum myEnum) {
std::visit([](auto t){
using Pixel = decltype(t)::type;
Foo<Pixel> a(...);
}, decodeUiEnum(myEnum));
}
int doSomeGraphicsMagic2(UiEnum myEnum, int blah) {
return std::visit([blah](auto t){
using Pixel = decltype(t)::type;
Bar<int, Pixel> a(...);
return a.frob();
}, decodeUiEnum(myEnum));
}
I have several classes that each of them has an ID and the Id is passed to the class as a template parameter:
typedef class1<1> baseClass;
typedef class2<2> baseClass;
typedef class<100> baseClass;
Now I need a map so if I can associate 1 with Class1 and 2 with Class2 and so on.
How can I create such vector? I am working on a header only library, so it should be a header only definition.
I am looking something that do the same thing that this code would do (if someone can compile it!):
std::map<int,Type> getMap()
{
std::map<int,Type> output;
output.add(1,class1);
output.add(2,class2);
output.add(100,class100);
}
The idea is that when I get as input 1, I create a class1 and when I receive 2, I create class2.
Any suggestion is very appreciated.
using this data, then I can write a function like this:
void consume(class1 c)
{
// do something interesting with c
}
void consume(class2 c)
{
// do something interesting with c
}
void consume(class3 c)
{
// do something interesting with c
}
void consume(int id,void * buffer)
{
auto map=getMap();
auto data= new map[id](buffer); // assuming that this line create a class based on map, so the map provide the type that it should be created and then this line create that class and pass buffer to it.
consume(data);
}
As a sketch:
class BaseClass { virtual ~BaseClass() = default; };
template<std::size_t I>
class SubClass : public BaseClass {};
namespace detail {
template<std::size_t I>
std::unique_ptr<BaseClass> makeSubClass() { return { new SubClass<I> }; }
template<std::size_t... Is>
std::vector<std::unique_ptr<BaseClass>(*)> makeFactory(std::index_sequence<Is...>)
{ return { makeSubclass<Is>... }; }
}
std::vector<std::unique_ptr<BaseClass>(*)> factory = detail::makeFactory(std::make_index_sequence<100>{});
We populate the vector by expanding a parameter pack, so we don't have to write out all 100 instantiations by hand. This gives you Subclass<0> at factory[0], Subclass<1> at factory[1], etc. up to Subclass<99> at factory[99].
If I understand correctly you want a map to create different types according to a given number.
If that is so, then the code should look something like this:
class Base
{
};
template <int number>
class Type : public Base
{
public:
Type()
{
std::cout << "type is " << number << std::endl;
}
};
using Type1 = Type<1>;
using Type2 = Type<2>;
using Type3 = Type<3>;
using CreateFunction = std::function<Base*()>;
std::map<int, CreateFunction> creators;
int main()
{
creators[1] = []() -> Base* { return new Type1(); };
creators[2] = []() -> Base* { return new Type2(); };
creators[3] = []() -> Base* { return new Type3(); };
std::vector<Base*> vector;
vector.push_back(creators[1]());
vector.push_back(creators[2]());
vector.push_back(creators[3]());
}
output:
type is 1
type is 2
type is 3
If you need only to create object, it would be enough to implement template creator function like:
template<int ID>
Base<ID> Create()
{
return Base<ID>();
}
And then use it:
auto obj1 = Create<1>();
auto obj2 = Create<2>();
// etc
Working example: https://ideone.com/urh7h6
Due to C++ being a statically-typed language, you may choose to either have arbitrary types that do a fixed set of things or have a fixed set of types do arbitrary things, but not both.
Such limitations is embodied by std::function and std::variant. std::function can have arbitrary types call operator() with a fixed signature, and std::variant can have arbitrary functions visit the fixed set of types.
Since you already said the types may be arbitrary, you may only have a fixed set of things you can do with such a type (e.g. consume). The simplest way is to delegate the hard work to std::function
struct Type
{
template<typename T>
Type(T&& t)
: f{[t = std::forward<T>(t)]() mutable { consume(t); }} {}
std::function<void()> f;
};
void consume(Type& t)
{
t.f();
}
What you are looking for is either the Stategy pattern:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class A {
public:
A() {}
virtual void doIt() {};
};
class Aa : public A {
public:
Aa() {}
virtual void doIt() {
std::cout << "do it the Aa way" << std::endl;
}
};
class Ab : public A {
public:
Ab() {}
virtual void doIt() {
std::cout << "do it the Ab way" << std::endl;
}
};
class Concrete {
public:
Concrete(std::string const& type) {
if (type == ("Aa")) {
_a.reset(new Aa());
} else if (type == "Ab") {
_a.reset(new Ab());
}
}
void doIt () const {
_a->doIt();
}
private:
std::unique_ptr<A> _a;
};
int main() {
std::vector<Concrete> vc;
vc.push_back(Concrete("Aa"));
vc.push_back(Concrete("Ab"));
for (auto const& i : vc) {
i.doIt();
}
return 0;
}
Will output:
do it the Aa way
do it the Ab way
I have a set of multiple C++ classes that have the same interface (not derived from each other though). I'm trying to wrap these to make them available in .NET.
I currently have a method that defines the wrapper class using C/C++ #defines and then I can subsequently instantiate classes with a simple line of code
However I can't debug this. Ideally I would like to be able to use a generic or a template. However I can't use a C++ type inside a generic which would be the ultimate way to solve this problem.
Has anyone any idea of how I can do this without using the dreaded macros?
EDIT:
OK Here is an example of the templated class I have written:
template< typename CPPResamplerClass >
ref class TResampler
{
CPPResamplerClass* pResampler;
public:
TResampler( int inputSampleRate, int outputSampleRate, int bufferLen ) :
pResampler( new CPPResamplerClass( inputSampleRate, outputSampleRate, bufferLen ) )
{
}
~TResampler()
{
this->!ResamplerName();
}
!TResampler()
{
if (pResampler)
{
delete pResampler;
pResampler = nullptr;
}
}
property int HistorySize
{
int get()
{
return pResampler->HistorySize();
}
}
array< float >^ ResampleAudio(array< float >^ in)
{
pResampler->Get
array< float >^ out = gcnew array< float >(in->Length);
cli::pin_ptr< float > pIn = &in[0];
cli::pin_ptr< float > pOut = &out[0];
unsigned int inLen = in->Length;
unsigned int outLen = out->Length;
if (pResampler->ResampleAudio(pOut, outLen, pIn, inLen))
{
System::Array::Resize(out, outLen);
return out;
}
return nullptr;
}
};
typedef TResampler< ::Vec::SpeexResample > SpeexResample;
I then want to access this from C# however SpeexResample does not exist. This could well be because I am using a typedef ...
Templates don't exist until they're instantiated. While you could instantiate one explicitly:
template ref class TResampler<SomeNativeClass>;
It wouldn't be exactly user-friendly to use from C#. The exported type will literally have angle brackets in its name. Good luck using that. In C# it's only doable through reflection.
The next best thing is to use derived types. Here's a minimal example:
#include "stdafx.h"
#include <iostream>
namespace CppCli {
class NativeClassA
{
int foo;
public:
NativeClassA(int foo) : foo(foo) { std::cout << "Built native class A" << std::endl; }
int getFoo() const { return foo; }
};
class NativeClassB
{
int foo;
public:
NativeClassB(int foo) : foo(foo) { std::cout << "Built native class B" << std::endl; }
int getFoo() const { return foo; }
};
template<typename NativeClass>
public ref class ManagedWrapper
{
NativeClass* ptr;
public:
ManagedWrapper(int foo)
: ptr(new NativeClass(foo))
{}
~ManagedWrapper()
{
this->!ManagedWrapper();
}
!ManagedWrapper()
{
if (ptr)
{
delete ptr;
ptr = nullptr;
}
}
property int Foo { int get() { return ptr->getFoo(); } }
};
public ref class ManagedWrapperA : ManagedWrapper<NativeClassA>
{
public:
ManagedWrapperA(int foo) : ManagedWrapper(foo) {}
};
public ref class ManagedWrapperB : ManagedWrapper<NativeClassB>
{
public:
ManagedWrapperB(int foo) : ManagedWrapper(foo) {}
};
};
Sure enough, ManagedWrapperA and ManagedWrapperB are visible from C#. Maybe you could macro these definitions and still get a decent debugging experience.
I am trying to create a helper class to abstract invoking function pointers. With feedback from others on SO, I am using a polymorphic class to achieve this (shown below). Templates are also used to reduce code duplication.
typedef void(*PFNFOO1) (int);
typedef void(*PFNFOO2) (double);
typedef void(*PFNBAR1) (long);
typedef void(*PFNBAR2) (float);
typedef struct FOO_TABLE
{
PFNFOO1 pfnFoo1;
PFNFOO2 pfnFoo2;
} FOO_TABLE;
typedef struct BAR_TABLE
{
PFNBAR1 pfnBar1;
PFNBAR2 pfnBar2;
} BAR_TABLE;
enum TABLE_TYPE
{
TYPE_FOO = 0,
TYPE_BAR = 1,
};
template <typename T>
class FooBarImpl : public FooBarBase
{
public:
// GetFunc is created to centralize needed validation before function is invoked
void* GetFunc(size_t funcOffset)
{
// do some validation
return reinterpret_cast<void*>(m_FooBarTable + funcOffset);
}
void* GetpfnFoo1() { return GetFunc(offsetof(T, pfnFoo1)); }
void* GetpfnFoo2() { return GetFunc(offsetof(T, pfnFoo2)); }
void* GetpfnBar1() { return GetFunc(offsetof(T, pfnBar1)); }
void* GetpfnBar2() { return GetFunc(offsetof(T, pfnBar2)); }
T* m_FooBarTable;
};
class FooBarBase
{
public:
static FooBarBase* CreateFooBar(TABLE_TYPE tableType)
{
switch(tableType)
{
case (TYPE_FOO) :
{
return new FooBarImpl<FOO_TABLE>();
}
break;
case (TYPE_BAR) :
{
return new FooBarImpl<BAR_TABLE>();
}
break;
}
}
virtual void* GetpfnFoo1() = 0;
virtual void* GetpfnFoo2() = 0;
virtual void* GetpfnBar1() = 0;
virtual void* GetpfnBar2() = 0;
};
int _tmain(int argc, _TCHAR* argv[])
{
{
FooBarBase *pFooBar = FooBarBase::CreateFooBar(TYPE_FOO);
// Initialize Foo table
auto p = reinterpret_cast<PFNFOO1>(pFooBar->GetpfnFoo1());
int parameter = 1;
p(parameter);
}
{
FooBarBase *pFooBar = FooBarBase::CreateFooBar(TYPE_FOO);
// Initialize Bar table
auto p = reinterpret_cast<PFNBAR2>(pFooBar->GetpfnBar2());
float parameter = 1.0f;
p(parameter);
}
return 0;
}
This is currently giving me complication errors as "C2039: 'pfnBar1' : is not a member of 'FOO_TABLE'" which makes sense because one of the implicit template specialization will try to do "offsetof(FOO_TABLE, pfnBar1)," which isn't allowed. I have two questions. First, I am wondering what's the best way to address this error. I think I can possibly address this by providing explicit template specializations for FooBarImpl and FooBarImpl, but I'd like to avoid doing that because it means that if I were to add a new table type later, I'd have to add another specialization. Also, it increases code duplication. Therefore, if there's a way to fix this issue without explicit template specialization, please let m know.
For my second question, if explicit template specialization cannot be avoided, I have also tried this:
class FooBarBase;
template <typename T>
class FooBarImpl : public FooBarBase
{
};
template <>
class FooBarImpl<FOO_TABLE> : public FooBarBase
{
public:
typedef FOO_TABLE T;
// GetFunc is created to centralize needed validation before function is invoked
void* GetFunc(size_t funcOffset)
{
// do some validation
return reinterpret_cast<void*>(m_FooBarTable + funcOffset);
}
void* GetpfnFoo1() { return GetFunc(offsetof(T, pfnFoo1)); }
void* GetpfnFoo2() { return GetFunc(offsetof(T, pfnFoo2)); }
T* m_FooBarTable;
};
template<>
class FooBarImpl<BAR_TABLE> : public FooBarBase
{
public:
typedef BAR_TABLE T;
// GetFunc is created to centralize needed validation before function is invoked
void* GetFunc(size_t funcOffset)
{
// do some validation
return reinterpret_cast<void*>(m_FooBarTable + funcOffset);
}
void* GetpfnBar1() { return GetFunc(offsetof(T, pfnBar1)); }
void* GetpfnBar2() { return GetFunc(offsetof(T, pfnBar2)); }
T* m_FooBarTable;
};
But for some reason, I keep getting this error "error C2504: 'FooBarBase' : base class undefined" even if it was working fine before I specialized the templates.
If anyone has ideas about these 2 questions, I'd really appreciate your feedback. Thanks.
Since I love progamming in both C# and C++, I'm about to implementing a C#-like event system as a solid base for my planned C++ SFML-GUI.
This is only an excerpt of my code and I hope this clarifies my concept:
// Event.h
// STL headers:
#include <functional>
#include <type_traits>
#include <iostream>
// boost headers:
#include <boost/signals/trackable.hpp>
#include <boost/signal.hpp>
namespace Utils
{
namespace Gui
{
#define IMPLEMENTS_EVENT(EVENTNAME, EVENTARGS) public: \
Utils::Gui::IEvent<EVENTARGS>& EVENTNAME() { return m_on##EVENTNAME; } \
protected: \
virtual void On##EVENTNAME(EVENTARGS& e) { m_on##EVENTNAME(this, e); } \
private: \
Utils::Gui::Event<EVENTARGS> m_on##EVENTNAME;
#define MAKE_EVENTFIRING_CLASS(EVENTNAME, EVENTARGS) class Fires##EVENTNAME##Event \
{ \
IMPLEMENTS_EVENT(EVENTNAME, EVENTARGS); \
};
class EventArgs
{
public:
static EventArgs Empty;
};
EventArgs EventArgs::Empty = EventArgs();
template<class TEventArgs>
class EventHandler : public std::function<void (void*, TEventArgs&)>
{
static_assert(std::is_base_of<EventArgs, TEventArgs>::value,
"EventHandler must be instantiated with a TEventArgs template paramater type deriving from EventArgs.");
public:
typedef void Signature(void*, TEventArgs&);
typedef void (*HandlerPtr)(void*, TEventArgs&);
EventHandler() : std::function<Signature>() { }
template<class TContravariantEventArgs>
EventHandler(const EventHandler<TContravariantEventArgs>& rhs)
: std::function<Signature>(reinterpret_cast<HandlerPtr>(*rhs.target<EventHandler<TContravariantEventArgs>::HandlerPtr>()))
{
static_assert(std::is_base_of<TContravariantEventArgs, TEventArgs>::value,
"The eventHandler instance to copy does not suffice the rules of contravariance.");
}
template<class F>
EventHandler(F f) : std::function<Signature>(f) { }
template<class F, class Allocator>
EventHandler(F f, Allocator alloc) : std::function<Signature>(f, alloc) { }
};
template<class TEventArgs>
class IEvent
{
public:
typedef boost::signal<void (void*, TEventArgs&)> SignalType;
void operator+= (const EventHandler<TEventArgs>& eventHandler)
{
Subscribe(eventHandler);
}
void operator-= (const EventHandler<TEventArgs>& eventHandler)
{
Unsubscribe(eventHandler);
}
virtual void Subscribe(const EventHandler<TEventArgs>& eventHandler) = 0;
virtual void Subscribe(const EventHandler<TEventArgs>& eventHandler, int group) = 0;
virtual void Unsubscribe(const EventHandler<TEventArgs>& eventHandler) = 0;
};
template<class TEventArgs>
class Event : public IEvent<TEventArgs>
{
public:
virtual void Subscribe(const EventHandler<TEventArgs>& eventHandler)
{
m_signal.connect(*eventHandler.target<EventHandler<TEventArgs>::HandlerPtr>());
}
virtual void Subscribe(const EventHandler<TEventArgs>& eventHandler, int group)
{
m_signal.connect(group, *eventHandler.target<EventHandler<TEventArgs>::HandlerPtr>());
}
virtual void Unsubscribe(const EventHandler<TEventArgs>& eventHandler)
{
m_signal.disconnect(*eventHandler.target<EventHandler<TEventArgs>::HandlerPtr>());
}
void operator() (void* sender, TEventArgs& e)
{
m_signal(sender, e);
}
private:
SignalType m_signal;
};
class IEventListener : public boost::signals::trackable
{
};
};
};
As you can see, I'm using boost::signal as my actual event system, but I encapsulate it with the IEvent interface (which is actually an abstract class) to prevent event listeners to fire the event via operator().
For convenience I overloaded the add-assignment and subtract-assignment operators. If I do now derive my event listening classes from IEventListener, I am able to write code without needing to worry about dangling function pointer in the signal.
So far I'm testing my results, but I have trouble with std::tr1::function::target<TFuncPtr>():
class BaseEventArgs : public Utils::Gui::EventArgs
{
};
class DerivedEventArgs : public BaseEventArgs
{
};
void Event_BaseEventRaised(void* sender, BaseEventArgs& e)
{
std::cout << "Event_BaseEventRaised called";
}
void Event_DerivedEventRaised(void* sender, DerivedEventArgs& e)
{
std::cout << "Event_DerivedEventRaised called";
}
int main()
{
using namespace Utils::Gui;
typedef EventHandler<BaseEventArgs>::HandlerPtr pfnBaseEventHandler;
typedef EventHandler<DerivedEventArgs>::HandlerPtr pfnNewEventHandler;
// BaseEventHandler with a function taking a BaseEventArgs
EventHandler<BaseEventArgs> baseEventHandler(Event_BaseEventRaised);
// DerivedEventHandler with a function taking a DerivedEventArgs
EventHandler<DerivedEventArgs> newEventHandler(Event_DerivedEventRaised);
// DerivedEventHandler with a function taking a BaseEventArgs -> Covariance
EventHandler<DerivedEventArgs> covariantBaseEventHandler(Event_BaseEventRaised);
const pfnBaseEventHandler* pBaseFunc = baseEventHandler.target<pfnBaseEventHandler>();
std::cout << "baseEventHandler function pointer is " << ((pBaseFunc != nullptr) ? "valid" : "invalid") << std::endl;
const pfnNewEventHandler* pNewFunc = newEventHandler.target<pfnNewEventHandler>();
std::cout << "baseEventHandler function pointer is " << ((pNewFunc != nullptr) ? "valid" : "invalid") << std::endl;
// Here is the error, covariantBaseEventHandler actually stores a pfnBaseEventHandler:
pNewFunc = covariantBaseEventHandler.target<pfnNewEventHandler>();
std::cout << "covariantBaseEventHandler as pfnNewEventHandler function pointer is " << ((pNewFunc != nullptr) ? "valid" : "invalid") << std::endl;
// This works as expected, but template forces compile-time knowledge of the function pointer type
pBaseFunc = covariantBaseEventHandler.target<pfnBaseEventHandler>();
std::cout << "covariantBaseEventHandler as pfnBaseEventHandler function pointer is " << ((pBaseFunc != nullptr) ? "valid" : "invalid") << std::endl;
return EXIT_SUCCESS;
}
The EventHandler<TEventArgs>::target<TFuncPtr>() method will only return a valid pointer if TFuncPtr is the exact same type as stored in the Functor, regardless of covariance.
Because of the RTTI check, it prohibits to access the pointer as a standard weakly-typed C function pointer, which is kind of annoying in cases like this one.
The EventHandler is of type DerivedEventArgs but nevertheless points to a pfnBaseEventHandler function even though the function ran through the constructor.
That means, that std::tr1::function itself "supports" contravariance, but I can't find a way of simply getting the function pointer out of the std::tr1::funcion object if I don't know its type at compile time which is required for a template argument.
I would appreciate in cases like this that they added a simple get() method like they did for RAII pointer types.
Since I'm quite new to programming, I would like to know if there is a way to solve this problem, preferrably at compile-time via templates (which I think would be the only way).
Just found a solution for the problem. It seems that I just missed a cast at a different location:
template<class TEventArgs>
class EventHandler : public std::function<void (void*, TEventArgs&)>
{
public:
typedef void Signature(void*, TEventArgs&);
typedef void (*HandlerPtr)(void*, TEventArgs&);
// ...
template<class TContravariantEventArgs>
EventHandler(const EventHandler<TContravariantEventArgs>& rhs)
: std::function<Signature>(reinterpret_cast<HandlerPtr>(*rhs.target<EventHandler<TContravariantEventArgs>::HandlerPtr>()))
{
static_assert(std::is_base_of<TContravariantEventArgs, TEventArgs>::value,
"The eventHandler instance to copy does not suffice the rules of contravariance.");
}
// ...
}
This works how it is supposed to work. Thank you nonetheless for giving me a smooth introduction into this really awesome community!