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

2021-12-13 00:00:00 templates c++

如果我有一个模板函数,例如这样:

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

template<typename T>
void func(const std::vector<T>& v)

有什么方法可以在函数内确定 T 是否是指针,或者我必须为此使用另一个模板函数,即:

Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:

template<typename T>
void func(const std::vector<T*>& v)

谢谢

推荐答案

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

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

相关文章