如果我有一个模板函数,例如这样:
template<typename T>
void func(const std::vector<T>& v)
有什么方法可以在函数中确定 T 是否是指针,或者我是否必须为此使用另一个模板函数,即:
template<typename T>
void func(const std::vector<T*>& v)
谢谢
最佳答案
确实,模板可以做到这一点,通过部分模板特化:
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;
}
如果在函数中你做的事情只对指针有效,你最好使用单独函数的方法,因为编译器会作为一个整体对函数进行类型检查。
但是,您应该为此使用 boost,它也包括:http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html
关于c++ - 确定 Type 是否是模板函数中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/301330/