基于嵌套typedef的存在类型决定 [英] Type decision based on existence of nested typedef

查看:98
本文介绍了基于嵌套typedef的存在类型决定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个模板结构,以便:

I need to define a template struct such that:

element<T>::type

的类型为:

T::element_type 

如果T包含一个名为element_type的(public)typedef,不包含此类typedef)

if T contains a (public) typedef named element_type, otherwise (if it does not contain such typedef)

element<T>::type

类型

T::value_type 

如果T是可变的且类型为

if T is mutable and of type

const T::value_type

如果T是常数。

我真的很努力,任何建议,非常感谢!

I am really struggling with this, any suggestion is very appreciated! :)

推荐答案

非常感谢您的帮助。 p>可能类似:

Maybe something like:

template <typename T>
struct has_element_type
{
    typedef char yes[1];
    typedef char no[2];

    template <typename C>
    static yes& test(typename C::element_type*);

    template <typename>
    static no& test(...);

    static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

template <typename T>
struct is_const
{
    static const bool value = false;
};


template <typename T>
struct is_const<const T>
{
    static const bool value = true;
};

template <typename, bool> // true -> const
struct value_type_switch; 

template <typename T>
struct value_type_switch<T, true>
{
    typedef const typename T::value_type type;
};

template <typename T>
struct value_type_switch<T, false>
{
    typedef typename T::value_type type;
};

template <typename, bool> // true -> has element_type
struct element_type_switch;

template <typename T>
struct element_type_switch<T, true>
{
    typedef typename T::element_type type;
};


template <typename T>
struct element_type_switch<T, false>
{
    typedef typename value_type_switch<T, is_const<T>::value>::type type;
};

template <typename T>
struct element
{
    typedef typename element_type_switch<T,
                                    has_element_type<T>::value>::type type;
};

这当然应该分开和组织。

This should of course be split up and organized.

这篇关于基于嵌套typedef的存在类型决定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆