C ++根据其模板定义类成员类型 [英] C++ define a class member type according to its template

查看:76
本文介绍了C ++根据其模板定义类成员类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的代码中,我们具有以下类:

In our code we have the following class:

template<class A, class B>
class myClass
{
    typedef std::list<Object<A,B>> MyList;
    typedef std::map<A, typename mList::iterator> MyMap

    MyList mList;
    MyMap mMap;
}

A类是元编程的,它可以是字符串,int等. 我想更改代码,以便在类A为元字符串"的情况下使用地图,否则将使用unordered_map.

class A is metaprogrammed and it can be a string, int and so on. I would like to change the code so in case class A is a "meta string" a map will be used, otherwise unordered_map will be used.

我试图添加更多的元编程,但是还没有成功:

I've tried to add some more meta programming but haven't succeeded yet:

template< class A, class B>
struct MapType // default
{
    typedef std::list<Object<A,B>> MyList;
    typedef std::unordered_map<A,B> MyMap;
}

//TODO struct with templated A (string) to use std::map

template<class A, class B>
class myClass
{
    ???? // if A ~ String define myMap to MAP . otherwise unordered

    MyList mList;
    MyMap mMap;
}

使用其他地图类型的其他建议也将受到赞赏.

any other suggestions for using different map type will be appreciated as well.

谢谢

推荐答案

一个简单的解决方案是使用std::conditional检查A是否与您的元字符串"类相同(我选择了std::string作为演示目的):

A simple solution would be to use std::conditional to check if A is the same as your "meta string" class (I picked std::string for demonstration purposes):

template<class A, class B>
class myClass
{
    std::list<Object<A,B>> mList;
    std::conditional_t<std::is_same<A,std::string>::value,
                       std::map<A,B>, std::unordered_map<A,B>> mMap;
};


另一种可能性是使用部分专业化:


Another possibility would be to use partial specialization:

template<class A, class B>
class myClass
{
    std::list<Object<A,B>> mList;
    std::unordered_map<A,B> mMap;
};

template<class B>
class myClass<std::string,B>
{
    std::list<Object<std::string,B>> mList;
    std::map<std::string,B> mMap;
};

这篇关于C ++根据其模板定义类成员类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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