2016-11-27 97 views
4

下面的类不会编译:decltype(some_vector):: 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, decltype(data)::size_type>> order; 
}; 

我得到以下编译器错误:

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


为什么说无法编译,而下面的代码工作正常?

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

回答

9

你需要告诉编译器的依赖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不依赖模板参数,所以有在这方面不含糊。

+2

只是完全丑陋! (但它有效......:/) –

+0

“而不是一个对象”,这碰到了头部的指甲。 – Surt