c++ - 类模板参数推导失败导致替换失败

标签 c++ templates c++17 type-deduction

我有一个简单的程序,我试图用它来测试 C++17 的类模板参数推导。

#include <iostream>
#include <list>

int main(int argc, const char * argv[]) {
    const char* a = "Hello";
    std::list x(1, a);
    return 0;
}

我想用 std::list 推导出类型为 const char* 的列表.但是,当尝试运行此代码时,出现错误 No viable constructor or deduction guide for deduction of template arguments of 'list' .特别是应该与此 list(size_type __n, const value_type& __x); 匹配的构造函数报告错误说:

Candidate template ignored: substitution failure [with _Tp = const char *, _Alloc = std::__1::allocator<const char *>]: 'size_type' is a protected member of 'std::__1::__list_imp<const char *, std::__1::allocator<const char *> >'

我很好奇为什么这不起作用,但像这样的程序完全符合 std::pair 的格式能够轻松推断出论点:

#include <iostream>
#include <list>

int main(int argc, const char * argv[]) {
    const char* a = "Hello";
    std::pair x(1, a);
    return 0;
}

谢谢。

最佳答案

clang 5 和 6 以及 gcc 7 和 8 可以毫无问题地编译您的代码。因此,您使用的编译器没有正确实现推导指南,或者使用的库没有适用于 std::list

的推导指南

关于c++ - 类模板参数推导失败导致替换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51315686/

相关文章:

html - 模板限制 - 只需要更改博客标题的颜色

c++ - 重载 operator->() 以更改被调用函数的返回值

c++ - 为什么 while 循环使用 cin.get() 函数会输出两次结果?

c++ - 通过引用将未知数组传递给函数 (C++)

c++ - 为什么这个 C++ 程序如此之快?

c++ - 创建函数变量 vector 时出现 "No matching function for call"错误

c++ - 什么是变量模板

c++ - 从长远来看,使用调试器和大量使用 C++ 模板是否不兼容?

clang - 在 Travis CI 上为 C++17 设置 Clang

c++ - 编译时检查和运行时检查 'at the same time'