代码之家  ›  专栏  ›  技术社区  ›  fuenfundachtzig

模板类函数T:如何判断T是否为指针?

  •  5
  • fuenfundachtzig  · 技术社区  · 16 年前

    this question

    template< typename T > bool Class::Fun <T*> ( T& variable ) {...}
    

    3 回复  |  直到 9 年前
        1
  •  22
  •   Kirill V. Lyadvinsky    16 年前

    无需专门化成员功能。在那个答案中,使用了独立结构。您仍然可以在类成员函数中自由使用它。

    // stand-alone helper struct
    template<typename T>
    struct is_pointer { static const bool value = false; };    
    template<typename T>
    struct is_pointer<T*> { static const bool value = true; };
    
    // your class
    class Class{
    public:
     template<typename T>
     void Fun(T& variable) {
         std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
     }
    };
    

    超载

    class Class {
    public:
     template<typename T>
     void Fun(T& variable) {
         std::cout << "is it not a pointer! " << std::endl;
     }
     template<typename T>
     void Fun(T*& variable) {
         std::cout << "is it a pointer! " << std::endl;
     }
    };
    
        2
  •  8
  •   moonshadow    16 年前
        3
  •  3
  •   gimpf    16 年前