Two important operators to type manipulation is typeid and decltype.
typeid return a object type_info with type information.
Some ways of verify types is:
- std::is_same
- typeid
- function overload
If you are using c++11 the better option should be std::is_same with a delctype (detects the type of variable), because it's compile time resolution.
vector<int> integers;
vector<double> doubles;
cout << is_same<vector<int>, decltype(integers)>::value << endl;
cout << is_same<vector<int>, decltype(doubles)>::value << endl;
cout << is_same<vector<double>, decltype(integers)>::value << endl;
cout << is_same<vector<double>, decltype(doubles)>::value << endl;
If you are using standard C++ (c++98), you can use typeid operator
vector<int> vectorInt;
vector<int> integers;
vector<double> doubles;
cout << ( typeid(integers) == typeid(vectorInt) ) << endl;
cout << ( typeid(doubles) == typeid(vectorInt) ) << endl;
You can use function overload and templates to resolve this types without unexpected broke.
At this way do you need write a function to each type to identify or the template function will return -1 (unknow) like identification.
template<typename T>
int getTypeId(T) {
return -1;
}
int getTypeId(vector<int>) {
return 1;
}
main() {
vector<int> integers;
vector<double> doubles;
vector<char> chars;
cout << getTypeId(integers) << endl;
cout << getTypeId(doubles) << endl;
cout << getTypeId(chars) << endl;
}