C++ Question

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

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

Answer

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.

Comments