我有一个模板模板方法,当使用不在命名空间中的模板调用它时,它工作正常。但是,当使用命名空间中的模板调用它时,出现 clang 错误。 MSVC 和 gcc 编译没有问题,但只有当我将标准设置为 C++17 时。
这是一个简单的例子
#include <vector>
template<template<typename> typename Template>
Template<int> foo() {
return {};
}
template <typename T>
using my_vector = std::vector<T>;
int main()
{
foo<my_vector>(); // compiles
foo<std::vector>(); // does not compile in clang or without C++17
}
没有 C++17 的 gcc 错误是:
<source>:14:5: error: no matching function for call to 'foo'
clang 错误是:
<source>:14:22: error: no matching function for call to 'foo<template<class _Tp, class _Alloc> class std::vector>()'
<source>:4:15: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'Template'
C++17 中的哪些更改允许这样做,是否是 clang 产生错误的错误?
最佳答案
vector 是
template<class T, class Allocator=std::allocator<T>>
class vector;
注意它需要 2 个参数。
在c++17采用 2 个参数的模板可以匹配 template<class>class
如果第二个违约;在 c++14这不是真的。
至于 c++17 中的 clang , 他们 found a bug in the standard如果您实现此功能:(通过上面评论中的@cpplearner)
(10): Despite being the resolution to a Defect Report, this feature is disabled by default in all language versions, and can be enabled explicitly with the flag -frelaxed-template-template-args in Clang 4 onwards. The change to the standard lacks a corresponding change for template partial ordering, resulting in ambiguity errors for reasonable and previously-valid code. This issue is expected to be rectified soon.
在c++14这可能有效:
template<template<class...> class Z>
Z<int> foo() {
return {};
}
因为有规则让class...
匹配任意数量的参数。
关于c++ - 使用命名空间中的模板调用模板模板方法时出现 False clang 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51724126/