【问题标题】:decltype(some_vector)::size_type doesn't work as template parameterdecltype(some_vector)::size_type 不能用作模板参数
【发布时间】:2017-04-11 03:57:57
【问题描述】:

以下类无法编译:

template<class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key>>
class MyContainer
{   
public:
    std::vector<Key, Allocator> data;
    std::vector<std::pair<std::size_t, decltype(data)::size_type>> order;
};

我收到以下编译器错误:

错误:“模板结构 std::pair”的模板参数列表中的参数 2 的类型/值不匹配


为什么编译失败,而下面的代码可以正常工作?

template<class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key>>
class MyContainer
{   
public:
    std::vector<Key, Allocator> data;
    std::vector<std::pair<std::size_t, std::size_t>> order;
};

【问题讨论】:

    标签: c++ c++11 templates vector decltype


    【解决方案1】:

    你需要告诉编译器依赖的size_type确实是一个类型(而不是一个对象,例如):

    template<class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key>>
    class MyContainer
    {   
    public:
        std::vector<Key, Allocator> data;
        std::vector<std::pair<std::size_t, typename decltype(data)::size_type>> order;
                                           ^^^^^^^^
    };
    

    std::size_t 不依赖于模板参数,所以这方面没有歧义。

    【讨论】:

    • “例如,不是一个物体”,一针见血。
    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    相关资源
    最近更新 更多