Jor*_*ega 21 c++ templates idioms typename c++14
我正在读这篇文章,并试图了解N3601是关于什么的.它说这个成语在网络搜索中出现了很多,但我找不到任何东西.是什么
template<typename T, T t>
Run Code Online (Sandbox Code Playgroud)
成语,它解决了什么,如何使用,什么是隐式模板参数,以及提案旨在解决的问题是什么?
Man*_*rse 15
正在解决的问题是从模板非类型参数中推导出类型.
鉴于:
template<typename T> void foo(T);
template<typename T, T> void bar();
Run Code Online (Sandbox Code Playgroud)
可以推断T
的foo
(例如,foo(10)
将导致T
被推断为int
),但它不是可以推断T
的bar
(bar<10>()
也根本无法编译,你必须把它写成bar<int,10>()
).
N3601建议通过引入语法来解决这个问题:
template<using typename T, T> void bar();
Run Code Online (Sandbox Code Playgroud)
这将允许bar<10>()
编译并导致T
推断出类型.
文章介绍是误导性的:实际上是成语
template <typename T, T t>
Run Code Online (Sandbox Code Playgroud)
它表示一个模板,它取决于该类型的类型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>();
}
Run Code Online (Sandbox Code Playgroud)
该提议是关于引入一些"语法糖",使符号更容易编写.
此外,上面给出的示例在其描述中是微不足道的(并且可能是错误的,因为模板参数需要constexpr
),但是本文描述了当前符号可能变得非常多毛,降低可读性和整体编程容易性的几种情况.
归档时间: |
|
查看次数: |
4083 次 |
最近记录: |