【问题标题】:Determine if Type is a pointer in a template function确定 Type 是否是模板函数中的指针
【发布时间】:2008-11-19 08:44:00
【问题描述】:

如果我有一个模板函数,例如这样:

template<typename T>
void func(const std::vector<T>& v)

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

template<typename T>
void func(const std::vector<T*>& v)

谢谢

【问题讨论】:

标签: c++ templates


【解决方案1】:

确实,模板可以做到这一点,通过部分模板专业化:

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

【讨论】:

  • 你在这里得到了一个多么孤独的小答案。 :)
  • @GMan haha​​ :) 你是怎么打我这个老答案的xD
  • @Johannes:嗯,我记得你在templates 标签上的排名异常高。列表,所以我想看看为什么。 :)
  • +1 有些答案永远不会过时,约翰内斯。这是一个这样的答案。
  • @WhozCraig 实际上这个答案已经过时了,因为对于 C++ 11 这个其他答案更好stackoverflow.com/a/15974269/55721
【解决方案2】:

C++ 11 内置了一个不错的小指针检查功能:std::is_pointer&lt;T&gt;::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';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多