std::is_same and std::get together

std::is_same and std::get together

本文关键字:std get together and is same      更新时间:2023-10-16

我试图检查特定类型是否进入类型列表(元组(。并遇到了一些麻烦:

#include  <tuple>
#include  <iostream>
template < typename T >
struct Type {
  using type = T;
};
int main() {
  constexpr auto Foo = std::make_tuple(Type<int>{},Type<int>{});
  if (std::is_same<int, std::get<0>(Foo)::type>::value)
    std::cout << "GG!" << std::endl;
  return 0;
}
test.cpp: In function ‘int main()’:
test.cpp:13:47: error: type/value mismatch at argument 2 in template parameter list for ‘template<class, class> struct std::is_same’
   if (std::is_same<int, std::get<0>(Foo)::type>::value)
                                               ^
test.cpp:13:47: note:   expected a type, got ‘std::get<0ul, {Type<int>, Type<int>}>(Foo)’

似乎std::get没有像我想要的那样向我展示类型。有人可以解释我为什么吗?

std::get<0>(Foo)::type在此

上下文中没有任何意义,因为std::get<0>(Foo)是一个值,而不是一个类型。

相反,请尝试以下操作:我们将使用 decltype() 来获取该表达式的类型(无需实际评估其值(。 这将产生Type<int>&类型。 我们将使用 std::decay 删除引用(因为Type<int>&::type也没有意义(,然后我们可以访问其type typedef。

这有点笨拙,但它有效:

if (
  std::is_same<
    int,
    // The decltype will be (Type<int>&). Decay to remove the
    // reference, cv-qualifiers, etc.
    std::decay< 
      decltype(std::get<0>(Foo))
    >::type::type
    // ^ Two ::types, one to extract the type from std::decay, one
    // for your Type<T> struct.
  >::value
) {
    std::cout << "GG!" << std::endl;
}

(演示(

当然可能有更好的方法来完成此检查,但这是一种方法。