什么是模板<类型名称 T、T > 习语?
What is the template<typename T, T t> idiom?
我正在阅读这篇文章,并试图理解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
),但是本文描述了几种情况,其中当前的符号可能变得非常复杂,降低了可读性和编程的总体易用性。
相关文章:
- 概念可以与 CRTP 习语一起使用吗?
- 复制和交换习语和迭代器
- 为什么当我做复制和交换习语时不调用我的复制构造函数?
- 漂亮的计数器习语的错误或格式错误的静态订单惨败?
- C++17 pimpl 习语上下文中的自定义迭代器
- 在 MyVector 中实现写入时复制习语
- 视觉 "extern __forceinline "是什么 c++ 习语?
- C 习语使用C库时,该C库期望功能指针
- 为什么 std::swap 不使用 swap 习语?
- 如何使用擦除删除习语从结构向量中删除值
- C++中的Singleton习语
- 在 C++11 中实现复制和交换习语的更好方法
- N 个并发读取器和 1 个生产者的习语或模式
- pImpl习语-将私有类实现放在cpp中有什么缺点
- 不能使用 pimpl 习语将用户定义的向量插入到封装的向量中
- Python -> C++ 习语:将 lambda 表达式存储在映射/容器中
- 安全方便的通用散列(用于 STL 无序集和映射)习语?
- 指向可配置实现的Pimpl习语
- 与构造函数参数相关的异常安全的习语
- 用C++处理身体习语