decltype(some_vector)::size_type doesn't work as template parameter

末鹿安然 提交于 2021-01-27 07:46:37

问题


The following class does not compile:

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;
};

I get the following compiler error:

error: type/value mismatch at argument 2 in template parameter list for ‘template struct std::pair’


Why does that fail to compile, while the following code works fine?

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;
};

回答1:


You need to tell the compiler that the dependent size_type is indeed a type (and not an object, for example):

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 doesn't depend on a template parameter, so there is no ambiguity in this regard.



来源:https://stackoverflow.com/questions/40827190/decltypesome-vectorsize-type-doesnt-work-as-template-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!