嵌套模板类中的std :: conditional

时间:2014-10-14 10:22:12

标签: c++ templates c++11 template-specialization template-meta-programming

我正在尝试以STL的风格实现RingBuffer。这意味着我也在为它实现一个迭代器,它必须作为const或非const工作。这只是迭代器部分:

#include <iterator>
#include <type_traits>

template <typename T> class RingBuffer {
public:
    class Iterator;
    // actual RingBuffer implementation here
};    

template <typename T, bool is_const=false> 
class RingBuffer<T>::Iterator {
public:
    typedef std::ptrdiff_t difference_type;
    typedef T value_type;
    typedef typename std::conditional<is_const, const value_type*, value_type*>::type pointer ;
    typedef typename std::conditional<is_const, const value_type&, value_type&>::type reference ;
    typedef std::random_access_iterator_tag iterator_category;

    // a bunch of functions here
    ...
};

GCC 4.8.0为我尝试访问迭代器的每一行都给出了错误,比如

no type named 'type' in 'struct std::conditional<is_const, const int*, int*>'

int替换为RingBuffer<T>已实例化的类型。我不明白。 is_const有一个默认值。为什么这不起作用?为什么GCC不会在错误消息中的false中替换,例如将int替换为value_type

解决方案可能很明显,但世界上所有的Google搜索都没有让我感到满意。模板仍然让我感到困惑。

1 个答案:

答案 0 :(得分:7)

如果您希望Iterator也模仿bool is_const,则必须将其声明为:

template <typename T> class RingBuffer {
public:
    template <bool is_const = false>
    class Iterator;
    // actual RingBuffer implementation here
};    


template <typename T>
template <bool is_const> 
class RingBuffer<T>::Iterator {
public:
    typedef std::ptrdiff_t difference_type;
    typedef T value_type;
    typedef typename std::conditional<is_const, const value_type*, value_type*>::type pointer ;
    typedef typename std::conditional<is_const, const value_type&, value_type&>::type reference ;
    typedef std::random_access_iterator_tag iterator_category;

    // a bunch of functions here
    ...
};

说明:Iterator是类模板的成员,但在原始代码中,Iterator本身是非模板类。 RingBuffer有一个模板参数T; Iterator是一个非模板类;在is_const出现的任何地方都没有。如果我们暂时删除外层课程会更清楚:

class Foo;

template <bool b = false>
class Foo
{
  // something
};

我相信上述情况显而易见。

相关问题