我正在阅读this,并试图了解N3601的内容。它说这个成语在网络搜索中出现了很多,但我找不到任何东西。什么是
template<typename T, T t>
成语,它解决了什么,如何使用,什么是隐式模板参数,以及提案旨在解决的问题?
答案 0 :(得分:15)
正在解决的问题是从模板非类型参数中推断出类型。
假设:
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
被推断。
答案 1 :(得分:5)
文章介绍有误导性:成语实际上是
template <typename T, T t>
它表示一个模板,它取决于该类型的T
类型和值t
。符号有点沉重,因为在大多数情况下,类型可以从值本身推断出来。
E.g。
// 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
),但是本文描述了当前符号可能变得非常多毛,降低可读性的几种情况。总体上易于编程。