简体   繁体   English

为什么允许使用模板作为非类型模板参数?

[英]Why is using a template as a non-type template parameter allowed?

I discovered that using a template as the »type« of a non-type template parameter seems to be allowed since C++20:我发现从 C++20 开始似乎允许使用模板作为非类型模板参数的 »type«:

template< typename T >
struct LiteralType {
    T a, b, c;
};

template< LiteralType t >
struct S {
    static constexpr auto value = t;
};

auto f() {
    return S< LiteralType< int >{} >::value;
}

(see https://godbolt.org/z/KdTcY8rqo ). (参见https://godbolt.org/z/KdTcY8rqo )。 Why exactly is this allowed?为什么这是允许的?

Informally, every instantiation of LiteralType is literal (or structural?) type, but where is this formally allowed in the standard?非正式地, LiteralType的每个实例化都是文字(或结构?)类型,但标准在哪里正式允许这样做?

Reading https://eel.is/c++draft/temp.param#6 briefly, only types are allowed for non-type template-parameters, not templates.简要阅读https://eel.is/c++draft/temp.param#6 ,非类型模板参数只允许类型,而不是模板。

The paragraph you read says "a placeholder for a deduced class type" .您阅读的段落说“推导类类型的占位符” This is standard verbiage for allowing class template argument deduction.这是允许类模板参数推导的标准用语。 Since C++17, we can declare variables as follows从 C++17 开始,我们可以如下声明变量

std::vector v{1, 2, 3};

The type of v is deduced via CTAD from the initializer, and the template name serves as placeholder. v的类型是通过 CTAD 从初始化程序中推导出来的,模板名称用作占位符。

The C++20 code you show is just a natural extension of this.您显示的 C++20 代码只是对此的自然扩展。 The non-type template parameter has its type deduced from the argument you provide as initializer (coincidently, even in C++17 we had deduction in this place, via auto placeholder types).非类型模板参数的类型是从您作为初始值设定项提供的参数推导出来的(巧合的是,即使在 C++17 中,我们也在这个地方通过auto占位符类型进行了推导)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM