【问题标题】:Is there any type trait which controls member type(not member variable) [duplicate]是否有任何类型特征控制成员类型(不是成员变量)[重复]
【发布时间】:2017-08-17 22:07:26
【问题描述】:

STL 带有许多类型特征,例如 std::is_pointer、std::is_reference 等...

假设我有一堂课

class A 
{
   using type_member = void;     
}

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

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

【问题讨论】:

  • 我相信成员变量和成员类型是不同的东西。成员类型可能不同,因为它们是纯类型。语言可能会为他们提供更简单的解决方案。你提出的问题对我没有帮助。
  • 查找void_t。
  • 看is_detected。
  • 各位大佬能不能用例子来写答案
  • 您能否解释一下为什么@MooingDuck 链接中的示例无法回答您的问题(并进行编辑以显示差异)?

标签: c++ c++11 typetraits


【解决方案1】:

如果 type_member 是 public (而不是 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
 }

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多