【问题标题】:how to get the type of a deferred template parameter如何获取延迟模板参数的类型
【发布时间】:2010-06-17 06:26:06
【问题描述】:

有没有办法获取类模板参数的延迟类型?

template <class TPtr>
struct foo {
    typedef TPtr ptr_type;
    typedef ??? element_type; /* shall be the type of a deferred TPtr*/
};

所以foo&lt;const char*&gt;::element_type 产生const char,foo&lt;std::vector&lt;int&gt;::iterator_type&gt;::element_type 产生int。

我知道我可以将value_type typedef 用于 c++ 迭代器(如std::vector&lt;int&gt;::iterator_type::value_type),但原始指针没有 value_type typedef,所以我不走运。

【问题讨论】:

    标签: c++ pointers templates


    【解决方案1】:

    如果TPtr 只能是一个指针,那么您正在寻找Boost's remove_pointer。

    如果您想知道它是如何工作的,它以这种方式使用部分专业化:

    template<typename T>
    struct RemovePointer;
    
    template<typename T>
    struct RemovePointer<T*>
    {
        typedef T Type;
    };
    
    int main()
    {
        RemovePointer<int*>::Type foobar; // foobar has the type int
        return 0;
    }
    

    如果TPtr 可以是迭代器或指针,您需要the iterator_traits class,它是标准库的一部分。在你的情况下,它是这样使用的:

    template <class TPtr> 
    struct foo { 
        typedef TPtr ptr_type;
        // The compiler won't know for sure if value_type is actually
        // a type until TPtr is known. The typename keyword is a hint
        // to the compiler so it doesn't cause an error.
        typedef typename iterator_traits<TPtr>::value_type element_type;
    };
    

    信不信由你,它也可以通过部分专业化来工作。基本上是这样定义的:

    // Primary template for iterators
    
    template<class Iterator>
    struct iterator_traits
    {
        typedef typename Iterator::difference_type difference_type;
        typedef typename Iterator::value_type value_type;
        typedef typename Iterator::pointer pointer;
        typedef typename Iterator::reference reference;
        typedef typename Iterator::iterator_category iterator_category;
    };
    
    // Partial specializations for pointers
    
    template<class T>
    struct iterator_traits<T*>
    {
        typedef ptrdiff_t difference_type;
        typedef T value_type;
        typedef T* pointer;
        typedef T& reference;
        typedef random_access_iterator_tag iterator_category;
    };
    
    template<class T>
    struct iterator_traits<const T*>
    {
        typedef ptrdiff_t difference_type;
        typedef T value_type;
        typedef const T* pointer;
        typedef const T& reference;
        typedef random_access_iterator_tag iterator_category;
    };
    

    这就是为什么iterator_traits 类同时适用于迭代器和指针的原因。

    【讨论】:

    • 使用迭代器解决方案以获得更通用的方法。它适用于指针。
    • 我已经编辑了我的答案以包含适用于迭代器的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多