降低C++中的模板复杂性

Pup*_*ppy 8 c++ visual-studio-2010 c++11

最近,我一直在使用一个较少使用的STL功能 - 自定义分配器,我需要一些严肃的帮助来减少我的语义开销.例如,无序映射的定义,它将文件名映射到一对int的无序映射,将shared_ptr映射到Token,但使用自定义分配器.

typedef std::pair<int, int> token_key_type;
typedef std::unordered_map<
    token_key_type, 
    std::shared_ptr<Token>,
    std::hash<token_key_type>,
    std::equal_to<token_key_type>,
    Allocator<
        std::pair<
            const token_key_type, 
            std::shared_ptr<
                Token
            >
        >
    >
> filename_map_value_type;
std::unordered_map<
    string, 
    filename_map_value_type,
    std::hash<string>,
    std::equal_to<string>,
    Allocator<
        std::pair<
            const string, 
            filename_map_value_type
        >
    >
> tokens;
Run Code Online (Sandbox Code Playgroud)

这是404个字符的定义.然后构造它,我必须为每个模板参数传递默认值,除了不能默认构造的Allocator,以及没有定义的桶数,导致另外168个字符只是为了构造该死的东西.当然,每次我想插入时都会再次相同,因为第一个地图的值类型也必须像这样构造.

有没有办法可以避免编写我自己的unordered_map而避免所有这些?它严重开始降低我的生产力.

编辑:对不起!一般来说,对于STL容器,我的意思是,不仅仅是unordered_map,它只是最糟糕的情况.我也使用常规map,unordered_set等来解决这个问题,并且无法编写一个函数来为我可能需要的所有可能的STL容器执行所有这些操作.

ice*_*ime 6

不幸的是,我无法提供完整且可编译的代码示例,因为我这里没有C++ 0x编译器.但是,我相信C++ 0x 模板别名在这里可能会有所帮助:

template<class Key, class Value>
using custom_unordered_map = std::unordered_map
    <
        Key,
        Value,
        std::hash<Key>,
        std::equal_to<Value>,
        Allocator<std::pair<const Key, Value>>
    >;

typedef custom_unordered_map<token_key_type, std::shared_ptr<Token>> filename_map_value_type;
typedef custom_unordered_map<std::string, filename_map_value_type> your_typedef_name;
Run Code Online (Sandbox Code Playgroud)

再一次,抱歉,如果这不编译.

另请注意,这在C++ 03中已经可以使用其他类型的"间接":

template<class Key, class Value>
struct custom_unordered_map
{
    typedef std::unordered_map
    <
        Key,
        Value,
        std::hash<Key>,
        std::equal_to<Value>,
        Allocator<std::pair<const Key, Value> >
    > type;
};

typedef custom_unordered_map<token_key_type, std::shared_ptr<Token> >::type filename_map_value_type;
typedef custom_unordered_map<std::string, filename_map_value_type>::type your_typedef_name;
Run Code Online (Sandbox Code Playgroud)


Dar*_*con 6

icecrime的解决方案也可以通过下面的代码在旧版编译器上稍稍丑陋地完成.您也可以添加工厂功能以简化构造.

template<typename K, typename V> struct unordered_map_type
{
    typedef std::unordered_map<
        K, 
        V,
        std::hash<K>,
        std::equal_to<K>,
        Allocator<
            std::pair<const K, V>
        >
    > type;
};

typedef std::pair<int, int> token_key_type;
typedef unordered_map_type<token_key_type, std::shared_ptr<Token> >::type filename_map_value_type;
Run Code Online (Sandbox Code Playgroud)