且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

确定 Type 是否是模板函数中的指针

更新时间:2023-11-27 14:51:58

确实,模板可以做到这一点,部分模板特化:

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.

但是,您应该为此使用 boost,它也包括:http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html

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