In C++, it is possible to use std::is_same
to check if two types are exactly identical. Is there a way to check if two types are identical except, maybe, a const
or a &
modifier? Here is an example:
#include <type_traits>
#include <iostream>
using namespace std;
int main() {
cout << boolalpha;
cout << is_same<char,int>::value << endl; // false - OK
cout << is_same<char,char>::value << endl; // true - OK
cout << is_same<char,const char>::value << endl; // false - should be true
cout << is_same<char,const char&>::value << endl; // false - should be true
}
Removing cv-qualifiers as well as returning a non reference type will be supported from C++20 onward std::remove_cvref
However as of current standard, you can use Type modifications functions in conjunction
template<class T1, class T2>
void print_is_same() {
std::cout << std::is_same<T1, T2>() << '\n';
}
int main() {
std::cout << std::boolalpha;
print_is_same<char, int>(); //false
print_is_same<char, char>(); //true
print_is_same<char, std::remove_const<const char>::type>(); //true
print_is_same<char, std::remove_const<std::remove_reference<const char &>::type>::type>(); //true
}
Or probably create a type alias such as
template<typename T>
using base_type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;