2012-04-09 91 views
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); 

回答

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{});