什么是模板<类型名称 T、T > 习语?

What is the template<typename T, T t> idiom?

本文关键字:gt 习语 类型 lt 什么      更新时间:2023-10-16

我正在阅读这篇文章,并试图理解N3601是关于什么的。上面说这个习语在网络搜索中经常出现,但是我什么也找不到。

是什么?
template<typename T, T t>

习惯用法,它解决了什么,如何使用,什么是隐式模板参数,该建议的目的是修复什么?

要解决的问题是从模板非类型形参中推断类型。

给定

:

template<typename T> void foo(T);
template<typename T, T> void bar();

可以将T演绎为foo(例如,foo(10)将导致T被演绎为int),但不可能将T演绎为bar (bar<10>()根本无法编译,您必须将其写成bar<int,10>())。

N3601建议通过引入语法来修复这个问题:

template<using typename T, T> void bar();

允许bar<10>()编译并推导出T类型

论文介绍误导人:成语实际上是

 template <typename T, T t>

表示依赖于类型T和该类型的值t的模板。符号有点重,因为在大多数情况下,类型可以从值本身推断出来。

// the current definition notation
template <typename T, T t> void f() { t.f(); };
//// the proposed definition notation
//// the parameter t depends on an implicit typename parameter T
// template <using typename T, T t> void f() { t.f(); };
struct foo {
    void f(){ 
        // some computation
    }
};
foo bar;
int main(){
    // the current instantiation notation
    f<foo,bar>(); 
    //// the proposed instantiation notation 
    //// we know that bar is of type foo, so we don't need to specify it
    // f<bar>();
}

这个建议是关于引入一点"语法糖",使符号更容易编写。

同样,上面给出的例子在其描述中是微不足道的(并且可能是错误的,因为模板参数需要是constexpr),但是本文描述了几种情况,其中当前的符号可能变得非常复杂,降低了可读性和编程的总体易用性。