![](/img/trans.png)
[英]Function template argument deduction works in gcc but not in msvc and clang
[英]Template template argument deduction failure with GCC (works with MSVC)
我有以下相当简单的功能模板:
template <class OrderedSetType, template<class> class SupersetType>
OrderedSetType f(const SupersetType<OrderedSetType>& superset)
{
return OrderedSetType();
}
叫做:
f(std::vector<std::string>());
并且编译器无法推断出template参数。 诊断消息不是特别有用:
<source>: In function 'int main()':
<source>:12:33: error: no matching function for call to 'f(std::vector<std::__cxx11::basic_string<char> >)'
f(std::vector<std::string>());
^
<source>:5:16: note: candidate: template<class OrderedSetType, template<class> class SupersetType> OrderedSetType f(const SupersetType<OrderedSetType>&)
OrderedSetType f(const SupersetType<OrderedSetType>& superset)
^
<source>:5:16: note: template argument deduction/substitution failed:
<source>:12:33: note: template parameters of a template template argument are inconsistent with other deduced template arguments
f(std::vector<std::string>());
^
为什么会发生错误? 在带有-std=c++14
GCC 7.3中发生,对于-std=c++17
则不会发生。 C ++ 17标准中的哪些更改允许此代码进行编译? 我可以使其针对C ++ 14进行编译吗?
这是现场演示: https : //godbolt.org/g/89BTzz
顺便说一句,明确指定模板参数并没有帮助。
PS同时,MSVC对此代码没有问题,但是clang 5和6即使在C ++ 17模式下也无法编译。 因此,要么clang有一个错误,无法编译符合标准的代码,要么GCC有一个错误,并且成功编译了本不应该的代码(使用-std=c++17
)。
试试看
template <template <typename...> class SupersetType,
typename FirstT, typename ... OthersTs>
FirstT f (SupersetType<FirstT, OthersTs...> const & superset)
{ return FirstT{}; }
或者也
template <template <typename...> class SupersetType, typename FirstT>
FirstT f (SupersetType<FirstT> const & superset)
{ return FirstT{}; }
问题是std::vector
不只接受一个类型,而只接受两个。 第二个是具有默认值的分配器。
因此,您必须考虑这个问题。
显然,您可以使用仅接受两种类型的template-template参数编写f()
template <template <typename, typename> class SupersetType,
typename FirstT, typename SecondT>
FirstT f (SupersetType<FirstT, SecondT> const & superset)
{ return FirstT{}; }
但是,如果您使用接受可变参数类型列表的模板参数,则可以使用更灵活的f()
(与更多容器匹配)
C ++ 17标准中的哪些更改允许此代码进行编译?
您在声明模板模板参数SupersetType
仅包含一个模板参数,但是模板模板参数 std::vector<std::string>
有两个,即std::string
和默认模板参数std::allocator<string>
。 在C ++ 17之前,它们不匹配并导致错误(然后必须使它们匹配才能解决问题),因为C ++ 17( CWG 150 )是允许的; 也就是说,允许模板模板参数使用默认模板参数,以使模板模板参数与更少的模板参数匹配。
template<class T> class A { /* ... */ }; template<class T, class U = T> class B { /* ... */ }; template <class ...Types> class C { /* ... */ }; 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 X<C> xc; // OK in C++17 after CWG 150 // Error earlier: not an exact match
虽然这不能解决您的问题,但提供了替代方法。
请记住,所有标准容器都有一个名为value_type
的公共类型。 这意味着您可以轻松跳过模板模板,而只需要
template<typename ContainerT>
typename ContainerT::value_type f(ContainerT const& superset)
{
return typename ContainerT::value_type();
}
只要您的SupersetType
遵循具有value_type
成员的标准容器,它就应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.