嵌套模板类中的std :: conditional

Mad*_*key 4 c++ templates template-specialization template-meta-programming c++11

我正在尝试以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
    ...
};
Run Code Online (Sandbox Code Playgroud)

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

no type named 'type' in 'struct std::conditional<is_const, const int*, int*>'
Run Code Online (Sandbox Code Playgroud)

替换已经实例化int的类型RingBuffer<T>.我不明白.is_const有一个默认值.为什么这不起作用?为什么不GCC替补多的false错误消息,喜欢它取代intvalue_type

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

Rei*_*ica 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
    ...
};
Run Code Online (Sandbox Code Playgroud)

Explanation:Iterator是类模板的成员,但在原始代码中,Iterator它本身是非模板类.RingBuffer有一个模板参数,T; Iterator是一个非模板类; 没有任何地方is_const可以出现.如果我们暂时删除外部类,它将变得更加清晰:

class Foo;

template <bool b = false>
class Foo
{
  // something
};
Run Code Online (Sandbox Code Playgroud)

我相信上述情况显然不会奏效.