0

我使用容器。

如果A是容器,则container_traits<A>::reference_container必须键入A.

如果容器RefContainer<C>is_base_of A,则container_traits<A>::reference_container必须键入 a C

以下代码执行此向上转换(或取消引用,正如我所说)。问题是,即使reference = false编译器检查是否C::reference_container作为类型存在,并且无法编译。

还有其他方法吗?

#include <iostream>
using namespace std;

template<typename C> struct RefContainer;

template<class C>
class container_traits
{
    template <typename R>
    static std::true_type ref_helper(const RefContainer<R>&);
    static std::false_type ref_helper(...);
public:
    constexpr static bool reference = decltype(ref_helper(std::declval<C>()))::value;
    typedef typename std::conditional<reference, typename C::reference_container, C>::type reference_container;
};

template<typename C>
struct RefContainer : public C { typedef typename container_traits<C>::reference_container reference_container; };
struct Container1 {};
struct Container2 {};
template<typename C> struct D : public RefContainer<C> {};
struct E : public RefContainer<D<RefContainer<Container1>>> {};

int main()
{
    container_traits<Container1>::reference_container e; // It is Container1
    container_traits<RefContainer<Container1>>::reference_container f; // dereference to Container1
    container_traits<D<Container2>>::reference_container // dereference to Container2
    container_traits<E>::reference_container h; // dereference to Container1
    return 0;
}
4

1 回答 1

1

只需创建助手类

template<class T, bool der>
struct hlp
{
   typedef T type;
}

template<class T>
struct hlp<RefContainer<T>, true>
{
   typedef T::reference_container type;
}
于 2013-03-27T11:41:21.313 回答