c++ - decltype(some_vector)::size_type 不能用作模板参数

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

下面的类不编译:

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

最佳答案

你需要告诉编译器依赖的 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 不依赖于模板参数,因此在这方面没有歧义。

关于c++ - decltype(some_vector)::size_type 不能用作模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827190/

相关文章:

C++内部类; "nm -C"输出中没有符号

c++ - 在 async_resolve 处理程序中出现 "Service not found"错误

c++ - boost序列化库有用吗?为什么不支持 "pointer to pointer"序列化?

c++ - std::count 的复杂性

javascript - Handlebars : TypeError: Cannot read property 'helperMissing' of undefined

c++ - 过滤嵌套动态元组(dynamic tuple of tuples)

c++ - 如何检索文件数字签名信息?

c++ - 设置加密++

c++ - Enable_if 作为模板参数

c++ - 模块会让模板编译更快吗?