c++ - 是否有可能有一个非递归的 at_c 实现?

标签 c++ templates recursion c++11 variadic-templates

很久以前,我看到了一种非递归实现,可以从类型序列/值序列中获取最后一个值/类型。它有一个很好的属性,即实例化的模板数量与序列包含的元素数量无关(并且是恒定的)。

实现很简单,如下

// 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)...))

它使用了一个简单的事实,即给定可变参数类型 X... 编译器可以非递归地生成另一个类型 TX 在那里。

所以,我想知道有没有办法扩展它以实现具有恒定数量的实例化模板(与元素数量无关)的 at_cnth 函数。

也可以表述为,给一个可变参数类型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_

关于c++ - 是否有可能有一个非递归的 at_c 实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17087625/

相关文章:

c++ - 初学者 C++ 练习的解决方案的意外输出

c++ - 使用 astyle 在一行中格式化 C++ 中的嵌套 namespace

c++ - 根据参数创建派生类的新实例

c++ - 混合别名和模板特化

html - CSS换行问题

c - 将带有 for 循环的递归函数转变为纯递归

python - 有多少种可能的组合?

javascript - 尾递归和斐波那契

c++ - Boost Socket 在 close() 上崩溃

c++ - 根据编译时条件在类型之间进行选择的惯用方式