如何检查两种类型是否相同,忽略 const 和引用?

How to check if two types are the same, ignoring const and reference?

在 C++ 中,可以使用 std::is_same 来检查两个类型是否完全相同。有没有办法检查两种类型是否相同,除了 const& 修饰符?这是一个例子:

#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
}

C++20 开始将支持删除 cv-qualifiers 以及返回非引用类型 std::remove_cvref

但是根据当前标准,您可以结合使用类型修改函数

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
}

或者可能创建一个类型别名,例如

template<typename T>
using base_type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;

我找到了另一种解决方案:我们可以添加它们而不是删除 const 和 &:

template<class T1, class T2>
bool is_almost_same_v = std::is_same_v<const T1&,const T2&>;

确实:

cout << is_almost_same_v<char,int> << endl;    // false
cout << is_almost_same_v<char,char> << endl;   // true
cout << is_almost_same_v<char,const char> << endl;  // true
cout << is_almost_same_v<char,const char&> << endl; // true