c++ - 使用命名空间中的模板调用模板模板方法时出现 False clang 错误

标签 c++ templates c++17 clang++

我有一个模板模板方法,当使用不在命名空间中的模板调用它时,它工作正常。但是,当使用命名空间中的模板调用它时,出现 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
}

Here is a live example.

没有 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 个参数。

采用 2 个参数的模板可以匹配 template<class>class如果第二个违约;在 这不是真的。

至于 中的 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.

这可能有效:

template<template<class...> class Z>
Z<int> foo() {
  return {};
}

因为有规则让class...匹配任意数量的参数。

关于c++ - 使用命名空间中的模板调用模板模板方法时出现 False clang 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51724126/

相关文章:

c++ - 三重与号 `&&&` 在 C++ 中代表什么?

django 检查模板上下文变量是否存在

文件的 C++ OpenSSL 哈希值不正确

c++ - 从2个模板类继承 `sameFunctionName<T>()` ==>不明确

c++ - 为枚举类重载强制转换运算符

c++ - 在鼠标悬停在填充栏上时更改 QProgressBar 的颜色/文本

c++ - 使用 Korge 编译 native 时抛出错误 "Unable to find library"

c++ - 非原始盒装类型的运算符

javascript - 未捕获的类型错误 : Cannot call method 'replace' of undefined backbone. js

c++ - 完美转发使用结构化绑定(bind)声明的变量