C++ 确定 Type 是否是模板函数中的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/301330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine if Type is a pointer in a template function
提问by Begui
If I have a template function, for example like this:
如果我有一个模板函数,例如这样:
template<typename T>
void func(const std::vector<T>& v)
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:
有什么方法可以在函数内确定 T 是否是指针,或者我必须为此使用另一个模板函数,即:
template<typename T>
void func(const std::vector<T*>& v)
Thanks
谢谢
回答by Johannes Schaub - litb
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.
如果在函数中你做的事情只对指针有效,你最好使用单独函数的方法,因为编译器对整个函数进行类型检查。
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
但是,您应该为此使用 boost,它也包括:http: //www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html
回答by Begui
C++ 11 has a nice little pointer check function built in: std::is_pointer<T>::value
C++ 11 内置了一个漂亮的小指针检查函数: std::is_pointer<T>::value
This returns a boolean bool
value.
这将返回一个布尔bool
值。
From http://en.cppreference.com/w/cpp/types/is_pointer
来自 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';
}