是否有任何类型特征控制成员类型(不是成员变量)

Is there any type trait which controls member type(not member variable)

本文关键字:类型 成员 变量 成员类 特征 控制 是否 任何      更新时间:2023-10-16

STL具有许多类型特征,如std::is_pointerstd::is_reference等...

假设我有一个班级

class A 
{
   using type_member = void;     
}

是否有任何类型特征用于控制类型成员并检查它是否存在?
类似is_type_member_exist<typename A::type_member>();

我既好奇 C++17 是否存在解决方案,也对 C++2003 感到好奇(在工作中我需要这个,我有 vs2010,它有一点 C++11 支持但不完整(。

如果type_memberpublic(而不是像你的问题中那样private(,我想你可以做类似的事情

#include <iostream>
template <typename X>
struct with_type_member
 { 
   template <typename Y = X>
   static constexpr bool getValue (int, typename Y::type_member * = nullptr)
    { return true; }
   static constexpr bool getValue (long)
    { return false; }
   static constexpr bool value { getValue(0) };
 };
class A 
 {
   public:
      using type_member = void;     
 };
int main ()
 {
   std::cout << with_type_member<int>::value << std::endl; // print 0
   std::cout << with_type_member<A>::value << std::endl;   // print 1
 }

希望这有帮助。