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

时间:2017-03-24 20:21:30

标签: c++ c++11 typetraits

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支持但不完整)。

1 个答案:

答案 0 :(得分:3)

如果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
 }

希望这有帮助。