繁体   English   中英

将模板成员 function 传递给模板

[英]Passing a template member function to a template

我有一组模板化在 integer N 和 class 上的类型,包含 N <= K 和 N >= 0 的所有类型,比如

template <int N> struct T { int i; }

template <int N> struct TContainer{
    std::vector<T<N>> vec;
    TContainer<N - 1> prev;

    template <int target_n> TContainer<target_n> & get() { return prev.get(); }
    template <> TContainer<N> & get<N>() { return *this; }
};

template <> struct TContainer<0>{
    std::vector<T<N>> vec;

    template <int target_n> TContainer<target_n> & get() {  }
    template <> TContainer<0> & get<0>() { return *this; }
};

class ContainsAll{
    TContainer<K> my_data;
    int my_instance_data;
};

ContainsAll 是否可能有某种 foreach function,它可以采用模板成员 function 对所有 N 的每个元素进行操作? 就像是

template<int N>
void for_each(TContainer<N> & container, template_function){
    for(auto it = container.vec.begin(); it != container.vec.end(); ++it){
        template_function(*it);
    }
    for_each<K - 1>(container.prev, template_function);
}

template<> void for_each<0>(TContainer<0> & container, template_function){
    for(auto it = container.vec.begin(); it != container.vec.end(); ++it){
        template_function(*it);
    }
}

所以我可以做

template <int N> add_to_T(T<N> & in){
    in.i += my_instance_data;
}

for_each(my_container, add_to_T);

您不能传递模板 function。但是您可以传递结构的实例(a function object ),其中包含模板 function,例如

template <typename F>
void for_each(TContainer<0>& container, F f)
{
    for (auto& t : container.vec)
        f(t);
}

template <int N, typename F>
void for_each(TContainer<N>& container, F f)
{
    for (auto& t : container.vec)
        f(t);
    for_each(container.prev, std::move(f));
}


struct TAdder {
    template <int N>
    void operator()(T<N>& t) const
    {
        t.i += N;
    }
};

for_each(c, TAdder{});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM