Jakub Mertlik
Jakub Mertlik

Reputation: 7

Array of templated structs

I have structs templated by int derived from a Base struct.

struct Base { int i; double d; }; 
template< int N > struct Derv : base { static const int mN = N; };

I need to make an array of Derv< N > where N can vary for each struct in that array. I know C/C++ does not allow arrays of objects of different types, but is there a way around this? I was thinking of separating the type information somehow (hints like pointers to Base struct or usage of union spring to my mind, but with all of these I don't know how to store the type information of each array element for usage DURING COMPILE TIME). As you can see, the memory pattern of each Derv< N > is the same.

I need to access the type of each array element for template specialization later in my code. The general aim of this all is to have a compile-time dispatch mechanism without the need to do a runtime "type switch" somewhere in the code.

Upvotes: 0

Views: 581

Answers (2)

Mahmoud Aladdin
Mahmoud Aladdin

Reputation: 546

I guess you can use ptr = dynamic_cast<Type>(element); .. ptr will equal to NULL if it's the wrong type. For example:

#include <map>
#include <cmath>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <iostream>


using namespace std;

struct Base { int i; double d; Base(){}; virtual ~Base(){};}; 
template< int N > struct Derv : public Base { static const int mN = N; ~Derv(){}; };

int main(int argc, char **argv){
    Base* arr[2];
    arr[0] = new Derv<10>;
    arr[1] = new Derv<5>;
    Derv<10> *ptr = dynamic_cast<Derv<10>* >(arr[0]);
    Derv<5> *ptr2 = dynamic_cast<Derv<5>* >(arr[0]);
    cout << ptr << endl << ptr2 << endl;
    return 0;
}
// That should print 
0x9571008 //ptr to object will differ every time.
0 // Null because of wrong type.

But you'll need to define virtual destructor in your struct for this to work, and/or a virtual function.

Upvotes: 1

Puppy
Puppy

Reputation: 146910

It is most certainly impossible. If you did

int i;
std::cin >> i;
some_magic_array X[size];

Then what is the type of X[i]? Oh, wait, you can't possibly know. It's nothing C++ specific, it's fundamentally impossible. That's why no some_magic_array will ever exist that permits this.

Unless you effectively use a std::tuple and guarantee that i is constexpr. Then you absolutely can do this with std::get<i>(tup);.

Upvotes: 1

Related Questions