代码之家  ›  专栏  ›  技术社区  ›  R Samuel Klatchko

这些模板可以变得清晰吗

  •  2
  • R Samuel Klatchko  · 技术社区  · 16 年前

    template <typename T, size_t SZ>
    void moo(T (&arr)[SZ])
    { ... }
    
    template <typename T>
    void moo(T *ptr)
    { ... }
    

    3 回复  |  直到 16 年前
        1
  •  5
  •   Georg Fritzsche    16 年前

    可以确定模板参数是否为数组:

    template<class T> struct is_array {
        enum { value = false }; 
    };
    template<class T, size_t N> struct is_array<T[N]> {
       enum { value = true }; 
    };
    template<class T> void f(T const&) { 
        std::cout << is_array<T>::value << std::endl;
    }
    

    enable_if ,以上可以明确。例如,使用Boost.TypeTraits:

    template <typename T, size_t SZ>
    typename boost::enable_if<boost::is_array<T>, void>::type
    f(T (&arr)[SZ]) {}
    

    但参考文献中根本不需要SFINAE:

    template<class T, size_t SZ> void f(T (&arr)[SZ]) {}
    template<class T>            void f(T* const& t)  {}
    

    Johannes提出了另一个更适合当前情况的选项—使用SFINAE来处理有问题的指针重载:

    template <typename T, size_t SZ> void f(T (&arr)[SZ]) {}
    template <typename T>
    typename boost::enable_if<boost::is_pointer<T>, void>::type
    f(T ptr) {}
    
        2
  •  2
  •   dyonis    15 年前

    template <typename T, size_t SZ>
    void moo(T (&arr)[SZ])
    { ... }
    
    template <typename T>
    inline void moo(T ptr) { __moo(ptr); }
    
    template <typename T>
    void __moo(T* ptr)
    { ... }
    
        3
  •  0
  •   wilhelmtell    16 年前

    int a[1] = {0}
    moo<int,1>(a);
    

    或者可以在const上重载:

    template<class T>
    void moo(T const* p) { }
    
    // ...
    moo(a); // not const, array
    
    int* p = 0;
    moo(p); // pointer