繁体   English   中英

嵌套模板类中的std :: conditional

[英]std::conditional in nested template class

我正在尝试以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 ,就像它为value_type替换了int

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

如果你希望Iterator也被bool is_const模板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
};

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM