template <class C, class T> void my_f(const C<T>& aContainer);
Hi all,
Is it possible and
how could I define a templated method like this :
template <class C, class T> void my_f(const C<T>& aContainer);
The syntax checker is not happy saying
If I define it like this :
1 2 3
|
template <class C, class T> void my_f(const C& aContainer) {
for (T c : aContainer) cout << c << " ";
}
|
The compiler is not happy. It says it
.
The alternative would be to define it for each container :
1 2
|
template <class T> void my_f(const std::set<T>& aSet);
template <class T> void my_f(const std::vector<T>& aVec);
|
Any idea please ?
Last edited on
I don't think you can do that because C has to be a complete type.
Containers has typedefs that you can use to get the element type from.
1 2 3 4
|
template <class C> void my_f(const C& aContainer)
{
for (const typename C::value_type& c : aContainer) cout << c << " ";
}
|
You are using C++11 so you can also use auto to do the same thing.
1 2 3 4
|
template <class C> void my_f(const C& aContainer)
{
for (const auto& c : aContainer) cout << c << " ";
}
|
Last edited on
template< template<class> class C, class T>
However note that, by instance,
std::vector doesn't hold just one template parameter.
Peter87 wrote: |
---|
Containers has typedefs that you can use to get the element type from. |
That's a lot better.
When you make your own container consider doing that typedef too.
Thanks very much Peter87.
Method 1 suffer from having to define it for each T.
Method 2 actually works with C++11.
¿what is the problem with method 1?
Topic archived. No new replies allowed.