Francis Cugler
Francis Cugler

Reputation: 7895

Comparing A Data Type in an If Statement

Is there a way to test a parameter's data type in an if statement? Here is an example of source code: it will not compile but it used to present my intentions.

typedef char cInt[sizeof(int)];
typedef char cFloat[sizeof(float)];
typedef char cDouble[sizeof(double)];

template<typename T>
char* convertToCharStr( const T& t ) {
    if ( t == int ) {
        cInt c = t;
        return c;
     }
     if ( t == float ) {
        cFloat c = t;
        return c;
     }
     if ( t == double ) {
        cDouble c = t;
        return c;
     }
     return nullptr;
}

As you can see, I am trying to create a template function that can take any default data types such as an int, unsigned int, float, double and depending on the data type it will create the appropriate char[] variable on the stack according to the data type passed in and store the data into the char[] and return the pointer out of the function.

I will leave this above the way it is, but as a note the character arrays should of been unsigned char.

Upvotes: 2

Views: 5108

Answers (1)

Rollen
Rollen

Reputation: 1210

Well, there are ways using typeid as done here Using typeid to check for template type , but I would suggest using template specialization instead, like so:

template<typename T>
char* convertToCharStr( const T& t ) {
    //Maybe you might feel it more appropriate to put a static assert here 
    return nullptr; 
}

template<>
char* convertToCharStr( const int& t ) {
    cInt c = t;
    return c;
}

template<>
char* convertToCharStr( const float& t ) {
    cFloat c = t;
    return c;
}

template<>
char* convertToCharStr( const double& t ) {
    cDouble c = t;
    return c;
}

See CPP Reference and this question for more of a discusion on it (and what else you can do..to avoid the pains of specialized templating). C++ templates specialization syntax

That being said, creating a variable on the stack and then returning a pointer to it is unsafe, as that variable will be unstacked on return of the function call and will likely be overwritten later on.

Upvotes: 7

Related Questions