abi*_*bir 14 c++ recursion templates variadic-templates c++11
很久以前我看过一个非递归实现来从类型序列/值序列中获取最后一个值/类型.它有一个很好的属性,实例化的模板数量是序列包含的元素数量的独立(和常量).
实现很简单,如下所示
// a struct that eats anything and everything
struct eat { template<class T> eat(T&&) {} };
// generates V matching with U
template<class U, class V> struct match { using type = V; };
template<class... X> struct back_
{
template<class U>
static U&& get(typename match<X, eat>::type..., U&& u)
{
return static_cast<U&&>(u); // forward
}
};
// simple macro to avoid repetition for trailing return type.
#define RETURNS(exp) -> decltype(exp) { return exp; }
// get the last value in meta O(1)
template<class T, class... Ts>
auto back(T&& t, Ts&&... ts) RETURNS( back_<Ts...>::get(static_cast<T&&>(t), static_cast<Ts&&>(ts)...))
Run Code Online (Sandbox Code Playgroud)
它使用一个简单的事实,即在给定可变参数类型X...的情况下,编译器可以非递归地生成T与Xs 一样多的其他类型.
所以,我想知道有没有办法扩展它来实现at_c或nth使用恒定数量的实例化模板(独立于元素数量).
它也可以表示为,给出一个可变类型X...和一些整数N,是否可以非递归地生成X...由N元素组成的子序列?
std::cout << back((int)(0),
(int*)(0),
(int**)(0),
(int***)(0),
(int****)(0),
(int*****)(0),
(int******)(0),
(int*******)(0),
1) << std::endl;
======================================================
nm -C que | fgrep eat
080489e2 W eat::eat<int*******>(int*******&&)
080489dc W eat::eat<int******>(int******&&)
080489d6 W eat::eat<int*****>(int*****&&)
080489d0 W eat::eat<int****>(int****&&)
080489ca W eat::eat<int***>(int***&&)
080489c4 W eat::eat<int**>(int**&&)
080489be W eat::eat<int*>(int*&&)
080489b8 W eat::eat<int>(int&&)
080489e2 W eat::eat<int*******>(int*******&&)
080489dc W eat::eat<int******>(int******&&)
080489d6 W eat::eat<int*****>(int*****&&)
080489d0 W eat::eat<int****>(int****&&)
080489ca W eat::eat<int***>(int***&&)
080489c4 W eat::eat<int**>(int**&&)
080489be W eat::eat<int*>(int*&&)
080489b8 W eat::eat<int>(int&&)
080489e7 W int&& back_<int*, int**, int***, int****, int*****, int******, int*******, int>::get<int>(eat, eat, eat, eat, eat, eat, eat, eat, int&&)
080489e7 W _ZN5back_IJPiPS0_PS1_PS2_PS3_PS4_PS5_iEE3getIiEEOT_3eatSB_SB_SB_SB_SB_SB_SB_SA_
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
426 次 |
| 最近记录: |