类模板参数推导失败会导致替换失败

Class template argument deduction fails leads to substitution failure

本文关键字:失败 替换 参数      更新时间:2023-10-16

我有一个简单的程序,我正试图用它来测试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的适当推导指南的库