Determine if Type is a pointer in a template function

后端 未结 2 1663
孤城傲影
孤城傲影 2020-11-30 00:53

If I have a template function, for example like this:

template
void func(const std::vector& v)

Is there any

相关标签:
2条回答
  • 2020-11-30 01:01

    C++ 11 has a nice little pointer check function built in: std::is_pointer<T>::value

    This returns a boolean bool value.

    From http://en.cppreference.com/w/cpp/types/is_pointer

    #include <iostream>
    #include <type_traits>
    
    class A {};
    
    int main() 
    {
        std::cout << std::boolalpha;
        std::cout << std::is_pointer<A>::value << '\n';
        std::cout << std::is_pointer<A*>::value << '\n';
        std::cout << std::is_pointer<float>::value << '\n';
        std::cout << std::is_pointer<int>::value << '\n';
        std::cout << std::is_pointer<int*>::value << '\n';
        std::cout << std::is_pointer<int**>::value << '\n';
    }
    
    0 讨论(0)
  • 2020-11-30 01:09

    Indeed, templates can do that, with partial template specialization:

    template<typename T>
    struct is_pointer { static const bool value = false; };
    
    template<typename T>
    struct is_pointer<T*> { static const bool value = true; };
    
    template<typename T>
    void func(const std::vector<T>& v) {
        std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
    }
    

    If in the function you do things only valid to pointers, you better use the method of a separate function though, since the compiler type-checks the function as a whole.

    You should, however, use boost for this, it includes that too: http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html

    0 讨论(0)
提交回复
热议问题