c++ - 不重复用作模板参数的类型

标签 c++ templates

鉴于下面的代码是否有更好的方法来纠正它不重复 typename std::iterator_traits<T>::iterator_category两次?

template<class T, class T2>
struct foo :
    bar<
        foo<T, T2>, typename 
        std::conditional<
            std::is_same<typename 
                std::iterator_traits<T>::iterator_category,  //Repeated
                std::random_access_iterator_tag
            >::value,
            std::bidirectional_iterator_tag, typename 
            std::iterator_traits<T>::iterator_category       //Repeated
        >::type
    >
{}

最佳答案

将其拆分(无论如何都应该这样):

// put in detail namespace/file or something in real code
template<class T, class T2>
struct foo_base
{
    typedef foo<T, T2> foo_type;
    typedef typename std::iterator_traits<T>::iterator_category category_type;

    static const bool random_access = std::is_same<category_type,
                                        std::random_access_iterator_tag>::value;
    typedef typename std::conditional<random_access,
                                        std::bidirectional_iterator_tag,
                                        category_type>::type tag_type;

    typedef bar<foo_type, tag_type>::type base_type;
}

template<class T, class T2>
struct foo :
   foo_base<T, T2>::base_type
{};

即使没有重复位,您仍应将其拆分,以将基类型逻辑与实际继承基类型分开。

关于c++ - 不重复用作模板参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4053473/

相关文章:

php - 自定义帖子类型WordPress模板如何在WordPress模板中添加自定义侧边栏

C++ 模板歧义

C++ 标准,有点困惑吗?

c++ - 重新排序 C++ 模板函数

c++ - 带有 tinyobjloader 的 OpenGL 顶点数组对象

c++ - 为什么类不能继承其父类的成员类型?

c++ - 你能举个例子说明什么时候真的需要 auto_ptr_ref 吗?

c++ - 在模板函数中使用 STL Sort?

c++ - 我可以根据属性重载函数模板吗?

c++ - 对结构成员使用泛型类型