Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long template parameter lists with generic class method definitions

Tags:

c++

templates

If I have a template class, for which I define a member function later in the file, is there a way to avoid repeating the long parameter list? For example

template<class tempParam1, class tempParam2, class tempParam3>
class Foo {
  ...
  int Bar(int funcParam1, int funcParam2, int funcParam3);
}
template<class tempParam1, class tempParam2, class tempParam3>
int Foo<tempParam1, tempParam2, tempParam3>::Bar(int funcParam1, int funcParam2, int funcParam3) {
  ...
}

Is there some way to keep that function definition line from being so long? Having a bunch of methods to define like that is making my code hard to read.

I tried a typedef like

template<class tempParam1, class tempParam2, class tempParam3>
typedef Foo<tempParam1, tempParam2, tempParam3> FooClass;
int FooClass::Bar(int funcParam1, int funcParam2, int funcParam3) {
  ...
}

But the compiler (g++) complained ("error: template declaration of ‘typedef’").

Thanks!

like image 652
Zane Beckwith Avatar asked Oct 21 '22 05:10

Zane Beckwith


1 Answers

If you define the member inside the class {} scope, you don't need to repeat the class template parameters.

Perhaps you can eliminate some parameters using the traits idiom, or otherwise compute several parameters from one.

Instead of

template< typename size_type, typename volume_type, typename width_type >

you could have

template< typename param_type >
  ...
    typedef typename measurement_traits< param_type >::size_type size_type;

etc.

C++11 does introduce using declarations which are effectively "templated typedefs", but they cannot be used in the nested-name-specifier of a function definition, which is what you are trying to simplify.

like image 147
Potatoswatter Avatar answered Nov 02 '22 11:11

Potatoswatter