gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:29:49 26 4
gpt4 key购买 nike

鉴于下面的代码是否有更好的方法来纠正它不重复 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com