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

37 c++ templates

如果我有模板功能,例如:

template<typename T>
void func(const std::vector<T>& v)
Run Code Online (Sandbox Code Playgroud)

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

template<typename T>
void func(const std::vector<T*>& v)
Run Code Online (Sandbox Code Playgroud)

谢谢

Joh*_*itb 87

实际上,模板可以做到这一点,部分模板专业化:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果在函数中你做的事情只对指针有效,你最好使用单独函数的方法,因为编译器类型 - 检查函数整体.

但是,您应该使用boost,它也包括:http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html

  • @WhozCraig 实际上,这个答案确实过时了,因为对于 C++ 11,这个其他答案更好 http://stackoverflow.com/a/15974269/55721 (2认同)

Beg*_*gui 47

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';
}
Run Code Online (Sandbox Code Playgroud)