← Back to team overview

dolfin team mailing list archive

Re: Template help

 

On Wed, Aug 31, 2011 at 09:20:22PM +0200, Martin Sandve Alnæs wrote:
> On 31 August 2011 21:13, Anders Logg <logg@xxxxxxxxx> wrote:
> > On Wed, Aug 31, 2011 at 09:10:21PM +0200, Martin Sandve Alnæs wrote:
> >> On 31 August 2011 16:12, Anders Logg <logg@xxxxxxxxx> wrote:
> >> > I want to declare the following function:
> >> >
> >> >  template<class S, class T>
> >> >  void apply_markers(S<T>& sub_domains, T sub_domain) const;
> >> >
> >> > S is a template class (either MeshFunction or MeshMarkers) and T is a
> >> > primitive type.
> >> >
> >> > The above declaration does not work. How should it be declared? I've
> >> > tried various other combinations without success.
> >>
> >>
> >> If you can make T a typedef in S, this works:
> >>
> >>
> >> template<typename V>
> >> class Foo
> >> {
> >> public:
> >>     typedef V value_type;
> >> };
> >>
> >> template<typename S>
> >> void apply_markers(S & sub_domains, typename S::value_type sub_domain)
> >> {
> >>   S s;
> >> }
> >>
> >> int main(int argc, char *argv[])
> >> {
> >>     Foo<int> a;
> >>     apply_markers< Foo<int> >(a, 3);
> >>     return 0;
> >> }
> >
> > Thanks. I think I just found another solution (remains to be seen,
> > currently compiling...). I simply do
> >
> > template<class S, class T>
> > void apply_markers(S& sub_domains, T sub_domain) const;
> >
> > S happens to be a template type over T, but it's not necessary to
> > write that out explicitly in the above function definition.
>
> Adding something like "typedef T value_type;" in S makes
> this more explicit, and is the standard approach in stl and boost.

So we should have this in all our container template classes?
(MeshFunction, Array, MeshMarkers, maybe others)

> Note that "typename" is supposedly considered nicer than "class"
> in template<> by modern C++ people. Because T doesn't have to
> be a class, but it has to be a typename. No technical difference though.

I've noticed but old habits are hard to shake...

> Also, the reason for the "typename" before S::value_type in my
> suggestion is that the compiler can't know whether S::value_type
> is a type or variable when parsing the code.

ok.

--
Anders


Follow ups

References