我的代码由 g++ 进行不同的解释c++14
and c++17
标准标志:
#include <iostream>
#include <vector>
template<class T, class A>
void func(const std::vector<T, A>&v)
{
std::cout << 1 << std::endl;
}
template<typename T, template <typename>class Vector>
void func(const Vector<T>&v)
{
std::cout << 2 << std::endl;
}
void f()
{
std::vector<int> v;
func(v);
}
int main()
{
f();
return 0;
}
当我尝试使用命令编译此代码时
g++ -std=c++14 -Wall -pedantic main.cpp
一切都很好。
但是当我尝试用命令编译这段代码时
g++ -std=c++17 -Wall -pedantic main.cpp
我收到此错误:
main.cpp: In function 'void f()':
main.cpp:19:11: error: call of overloaded 'func(std::vector<int>&)' is ambiguous
func(v);
^
main.cpp:5:6: note: candidate: 'void func(const std::vector<_Tp, _Alloc>&) [with T = int; A = std::allocator<int>]'
void func(const std::vector<T, A>&v)
^~~~
main.cpp:11:6: note: candidate: 'void func(const Vector<T>&) [with T = int; Vector = std::vector]'
void func(const Vector<T>&v)
从 C++17 标准的角度来看,我无法弄清楚这段代码有什么问题。
自 C++17 以来,行为发生了变化。
在 C++17 之前,该代码可以工作,因为std::vector https://en.cppreference.com/w/cpp/container/vector有两个模板参数(第二个有默认参数std::allocator<T>
),而模板模板参数Vector
被声明只有一个,它们与第二个不匹配func
不会被考虑。
自 C++17 起 (CWG 150 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#150),默认模板参数允许模板模板参数 https://en.cppreference.com/w/cpp/language/template_parameters#Template_template_arguments匹配模板参数较少的模板参数。这意味着两者func
成为有效的候选人,然后导致歧义。
template<class T> class A { /* ... */ };
template<class T, class U = T> class B { /* ... */ };
template<template<class> class P> class X { /* ... */ };
X<A> xa; // OK
X<B> xb; // OK in C++17 after CWG 150
// Error earlier: not an exact match
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)