如果我有一个模板函数,例如这样:
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
这篇关于确定 Type 是否是模板函数中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)