c++c++11identifiertypeinfo

Instantiating identifier with dynamic type info on standard types


I know there are easier ways to do this, but this is what I am asking.

Suppose you have one template function, function1, and another template function, function2.

The function definitions are as follows:

template <typename A>
void function1(A x) // typename A is part of a class-template function
                    // the typename is declared in the class instantiation
                    // and passed to function2

template <typename B>
void function2(B y) // I know I can use typeinfo(y).name to get name
                    // this returns a const char* 'm' 
                    // 'm' stands for unsigned long on my sytem

The reference for the 'm' assertion is here: Strange output of std::typeid::name()

As I said, I know it is possible to figure out (deduce) the parameter a function receives with

const char* x = typeinfo(parameter).name;
// returns const char* 'm' on my machine

Is it possible, if a function receives a generic parameter, to also instantiate a new object of the same type. Something like:

<x> foo;
// where x represents the const char* = 'm'
// which in turn is represented by unsigned long on my system
// so foo would be an uninstantiated unsigned long identifier

I see here: Creating a new object from dynamic type info that it isn't possible for objects, but I am wondering if it is possible for internal types like int.

Thanks!


Solution

  • Use templates for this?

    template <typename T> 
    void foo(T yourParam)
    {
        T newVar;  //Use of the deduced type to declare new variable
    }
    

    You can also use decltype:

    decltype(parameter) newVar;
    

    As you seem insistent on using the const char *, and you're asking about builtin types, why not use a switch statement?

    switch(x)
    {
        case 'm' : {
            unsigned long foo;
            //functionality
            break;
        }
        //other cases
        default : break;
    }