Reputation: 577
I have a class that looks like this
class Foo
{
public:
template<class T>
A(T * ptr) { ptr_ = reinterpret_cast<void*>(ptr_);}
template<class T>
T * get() { return reinterpret_cast<T*>(ptr_);}
private:
void * ptr_;
};
At compile time, I know exactly what elements are going to be in my array. Is there a way I can annotate this class such that an array of Foo pointers knows which type it should get?
Basically I want to call Foo[i]<T>->apply()
and not have to look up the type at runtime, since it should know at compile time what kind of object it is.
P.S. Please don't suggest virtual functions, I know they are a valid solution but I want to know if this is possible because I do have all type information at compile time.
Upvotes: 0
Views: 202
Reputation: 25613
My understanding of your question is as follows:
You want to have some kind of table/array which contains object pointers and member function pointers to the corresponding objects. Later you want to call that "pairs" without any virtual function in between.
Maybe you can start with this approach:
struct A
{
void Foo() { std::cout << "A Foo" << std::endl; }
void Bar() { std::cout << "A Bar" << std::endl; }
};
struct B
{
void Do() { std::cout << "B Do " << std::endl; }
void Go() { std::cout << "B Go " << std::endl; }
};
template < typename T, auto MEM_PTR >
void Call( void* obj)
{
(((T*)obj)->*(MEM_PTR))();
}
using OBJ_FUNC_PAIR = std::pair< void* , void(*)(void*) >;
A a;
B b;
std::array< OBJ_FUNC_PAIR ,4 > arr
{
{
{ (void*)&a, &Call<A, &A::Foo>},
{ (void*)&a, &Call<A, &A::Bar>},
{ (void*)&b, &Call<B, &B::Do > },
{ (void*)&b, &Call<B, &B::Go > }
}
};
int main()
{
for ( auto& pair: arr )
{
(*pair.second)( pair.first );
}
}
Upvotes: 1