3

Can anybody please tell me how to make the following pseudo-code compatible with GCC4? I wonder how it works under MSVC...

typedef int TypeA;
typedef float TypeB;

class MyClass
{
// No base template function, only partially specialized functions...
    inline TypeA myFunction<TypeA>(int a, int b) {} //error: Too few template-parameter-lists
    template<> inline TypeB myFunction<TypeB>(int a, int b) {}
};
Ryan
  • 1,451
  • 2
  • 27
  • 36

1 Answers1

5

The proper way of coding that construct would be:

typedef int TypeA;
typedef float TypeB;
class MyClass
{
    template <typename T> 
    T myFunction( int a, int b );
};
template <> 
inline TypeA MyClass::myFunction<TypeA>(int a, int b) {}
template <> 
inline TypeB MyClass::myFunction<TypeB>(int a, int b) {}

Note that the template member function has to be declared inside the class declaration, but specializations must be defined outside of it, at namespace level.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • @Ryan: You do not need to implement it as long as it is never used. If some code tries to call that function with a template argument other than `double` or `int`, it will compile (the declaration is present) but it will fail to link (there is no definition for the non-specialized template). Also, and since there are only two instantiating types, you can move the specializations to a single translation unit and manually instantiate them (don't forget to add a comment to the function so that others know that you can only use that template with the two types!) – David Rodríguez - dribeas May 17 '11 at 12:59
  • Thanks for clarification, David! I'm sorry to ask so much, but can you please also tell me, how to solve this kind of problem in case of template functions? If I define a template function and several specialized functions in a global namespace, I get the 'Specialization of ... after instantiation' error... – Ryan May 17 '11 at 13:13
  • That error means that the function template has already been instantiated at the point where the compiler is processing the specializations. You can probably resolve it by moving code around, so that the template declaration and the specializations are together and before any use of the template. – David Rodríguez - dribeas May 17 '11 at 13:36