Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing typenames in C++

Tags:

c++

I typed this into a template function, just to see if it would work:

if (T==int)

and the intellisense didn't complain. Is this valid C++? What if I did:

std::cout << (int)int;  // looks stupid doesn't it.
like image 457
Alexander Rafferty Avatar asked Oct 14 '10 05:10

Alexander Rafferty


People also ask

Can we compare two data types in C?

If both operands have the same type, then no further conversion is needed. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

How do you check if a variable is a string in C?

You can call isdigit() on each character of the string, and if it's true for all characters you have an integer, otherwise it's some alphanumeric string. You can also call strtol to parse the string as an integer. The second argument returns a pointer to the first non-numeric character in the string.

How do you compare data types in C++?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.

What is the size of data types in C?

The size is typically about 32-bits or 4 bytes on a 16/ 32-bit compiler. Yet, it varies depending on what compiler we are using. There is no specification of the data types sizes according to the C standard, except the character.


1 Answers

Just to fit your requirement you should use typeid operator. Then your expression would look like

if (typeid(T) == typeid(int)) {
    ...
}

Obvious sample to illustrate that this really works:

#include <typeinfo>
#include <iostream>

template <typename T>
class AClass {
public:
    static bool compare() {
        return (typeid(T) == typeid(int));
    }
};

void main() {
    std::cout << AClass<char>::compare() << std::endl;
    std::cout << AClass<int>::compare() << std::endl;
}

So in stdout you'll probably get:

0
1
like image 124
Keynslug Avatar answered Oct 12 '22 23:10

Keynslug