C++ 带模板的递归类型向上转换
我处理容器 如果C++ 带模板的递归类型向上转换,c++,templates,sfinae,C++,Templates,Sfinae,我处理容器 如果A是一个容器,那么container\u traits::reference\u container必须键入A 如果容器RefContainer是A的基础,则container\u traits::reference\u container必须键入AC 下面的代码执行此向上转换(或者如我所说的取消引用)。 问题是,即使reference=false编译器检查C::reference\u容器是否作为类型存在,并且编译失败 还有其他方法吗 #include <iostream&
A
是一个容器,那么container\u traits::reference\u container
必须键入A
如果容器RefContainer
是A
的基础,则container\u traits::reference\u container
必须键入AC
下面的代码执行此向上转换(或者如我所说的取消引用)。
问题是,即使reference=false
编译器检查C::reference\u容器
是否作为类型存在,并且编译失败
还有其他方法吗
#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;
}
#包括
使用名称空间std;
模板结构RefContainer;
模板
类容器特性
{
模板
静态std::true_type ref_helper(const RefContainer&);
静态std::false_类型ref_helper(…);
公众:
constexpr static bool reference=decltype(ref_helper(std::declval())::value;
typedef typename std::conditional::type reference_容器;
};
模板
struct RefContainer:public{typedef typename container_traits::reference_container reference_container;};
结构容器1{};
结构容器2{};
模板结构D:public RefContainer{};
结构E:公共引用容器{};
int main()
{
container\u traits::reference\u container e;//它是Container1
container\u traits::reference\u container f;//取消对Container1的引用
容器特征::引用容器//取消对容器2的引用
container\u traits::reference\u container h;//取消对Container1的引用
返回0;
}
只需创建助手类
template<class T, bool der>
struct hlp
{
typedef T type;
}
template<class T>
struct hlp<RefContainer<T>, true>
{
typedef T::reference_container type;
}
模板
结构hlp
{
T型;
}
模板
结构hlp
{
typedef T::参考_容器类型;
}
main()中的最后两行未能到达Container1。之所以会发生这种情况,是因为使用这种方法,您只捕获RefContainer,而不捕获从RefContainer派生的类。@Chameleon错过了这一点,我更改了答案。使用它而不是std::conditional