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