c++ - 是否保证模板模板参数调用用户提供的推导指南

标签 c++ templates language-lawyer c++17 template-argument-deduction

考虑一个例子:

#include <type_traits>
#include <string>

template <template <class> class TT> //#1
struct Foo {
   static void foo() {
      static_assert(std::is_same_v<decltype(TT("abc")), TT<std::string>>);
   }
};

template <class T>
struct Bar {
    Bar(T) {}
};

template <class T>
Bar(T) -> Bar<std::string>; //#2

int main() {
    Foo<Bar>::foo();
}

[clang]以及[gcc]在推导模板模板参数(#1)的模板参数时,两者似乎都使用用户提供的推导指南(#2)。它是否符合标准?

最佳答案

是的,这是符合标准的。

根据 [dcl.type.simple]/2 :

A type-specifier of the form typenameopt nested-name-specifieropt template-name is a placeholder for a deduced class type ([dcl.type.class.deduct]). The template-name shall name a class template that is not an injected-class-name.

[temp.param]/3 :

A type-parameter whose identifier does not follow an ellipsis defines its identifier to be a typedef-name (if declared without template) or template-name (if declared with template) in the scope of the template declaration.

TT 是用 template 声明的类型参数,这使它成为 template-name 并因此成为推导类类型的占位符.所有通常的规则都适用。

关于c++ - 是否保证模板模板参数调用用户提供的推导指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46610383/

相关文章:

c++ - 重载 + 运算符的级联

c++ - 当模板有默认参数时省略尖括号

jQuery 模板 - 替换 DIV 内容

c++ - 模板中的嵌套类型名称

c++ - 局部自动函数变量的销毁与返回值的构造之间的顺序

C++创建可变数量的数组

c++ - CUDA 5.0 头文件

C++ 可变函数语法

c - 做像 foo(x, &x) 这样的事情安全吗?

c++ - 简化类方法的多重定义