将模板成员函数传递给模板

3

我有一组基于整数N的类型模板,还有一个类来包含所有满足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函数,能够接受一个模板成员函数,以便对所有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);
1个回答

2
你无法传递一个模板函数,但你可以传递一个结构体实例(一个“函数对象”),它包含一个模板函数,例如:
您无法传递一个模板函数。但是您可以传递一个结构体的实例(即“函数对象”),其中包含一个模板函数,例如:
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{});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接