[英]Determine if Type is a pointer in a template function
如果我有一个模板 function,例如这样:
template<typename T>
void func(const std::vector<T>& v)
有什么方法可以在 function 中确定 T 是否是指针,或者我是否必须为此使用另一个模板 function,即:
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 ++ 11有一个很好的小指针检查函数: std::is_pointer<T>::value
这将返回一个布尔bool
值。
来自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';
}
从 C++17 开始,有一个更短的内置结构std::is_pointer_v<T>
:
#include <type_traits>
int main()
{
class A {};
static_assert(
not std::is_pointer<A>::value
&& not std::is_pointer_v<A>); // equivalent to above, but shorter
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.