Home > Software design >  Create object of type specified in a given char
Create object of type specified in a given char

Time:11-04

My header file defines multiple classes with single character names; i.e class A, class B, class C etc. each class supports .getname() which returns the class name as a char, given a randomly generated char I'm am challenged with using a template to return the size using sizeof().

I'm so far unable to figure out how to define the class type given a char value.

my hope is to allow the following to print the size of the A class, for simplification purposes I've assigned testChar to 'A', however in reality it could be any random char for which a matching class name exists;

class A
{
private:
    char name;

public:
    A(){name='A';}
    char getName(){return name;}
};

template <typename X>
void printSize()
{
    X newObject;
    std::cout<<sizeof(newObject)<<std::endl;
}
int main()
{
    char testChar = 'A';
    printSize<testChar>();
    return 0;
};

and help would be greatly appreciated!

edit: I should have also mentioned that the random char given could be any char value and the class types are not meant to be explicitly referenced using switch cases or if else statements.

CodePudding user response:

You can use decltype as shown below:

 printSize<decltype(testChar)>();

But note testChar is a char variable. If on the other hand, testChar was a class type variable then decltype(testChar) would be the type of that class. For example,

A testChar;//testChar is of type A
printSize<decltype(testChar)>(); //decltype(testChar) is of type A

You can also write:

printSize<B>(); // directly write the name of the class that you want 

CodePudding user response:

If I understand correctly, you want to get the size of a class based on the character provided in the template parameter.

Sadly, for now, there is no easy and straightforward way to do that in C since it doesn't support reflection (yet), but you could manually map each individual char value to the corresponding class and print its size:

#include <cstddef>
// ...

template <char X>
void printSize();
template <>
void printSize<'A'>() {
    std::cout << sizeof(A) << std::endl;
}
// Do the same for 'B', 'C', 'D', etc...

// ...

Then you'd be able to do this:

// ...

int main() {
    constexpr auto testChar = 'A';
    printSize<testChar>();
    return 0;
}

Demo

  • Related