0

The following example code does not compile:

#include <iostream>

template<bool Enable>
struct BaseTemplate
{

 template< typename Policy>
 void templateMethod(Policy& policy);
};


template<bool Enable>
template<typename Policy>
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
{
        std::cout << "template method" << std::endl;
};


int main()
{
BaseTemplate<true> base;
float v = 3.0;
base.templateMethod(v);
};

It fails with this error:

$ g++-4.8 -std=c++11 mtempl.cpp -o ./xMtempl
mtempl.cpp:15:65: error: function template partial specialization ‘templateMethod<Policy>’ is not allowed
 void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)

Now, this is the thing that annoys me: this is not a specialization, I'm just defining the method template separately from the declaration!

If I replace

template<bool Enable>
template<typename Policy>
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
{
        std::cout << "template method" << std::endl;
};

with this

template<bool Enable, typename Policy>
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
{
        std::cout << "template method" << std::endl;
};

The error I get is:

mtempl.cpp:16:65: error: template-id ‘templateMethod<Policy>’ in declaration of primary template
 void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
                                                                 ^
mtempl.cpp:16:6: error: prototype for ‘void BaseTemplate<Enable>::templateMethod(Policy&)’ does not match any in class ‘BaseTemplate<Enable>’
 void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
      ^
mtempl.cpp:9:7: error: candidate is: template<bool Enable> template<class Policy> void BaseTemplate<Enable>::templateMethod(Policy&)
  void templateMethod(Policy& policy);

What's the problem? How do I define the method template separately from the declaration?

lurscher
  • 24,822
  • 27
  • 117
  • 183

1 Answers1

1
template<bool Enable>
template<typename Policy>
void BaseTemplate<Enable>::templateMethod<Policy>(Policy& policy)
{
    // stuff
};

This is a specialization. Remove <Policy> to have a simple definition.

template<bool Enable>
template<typename Policy>
void BaseTemplate<Enable>::templateMethod(Policy& policy)
{
    // stuff
};

BTW, you've extra semicolons at the end of methods.

Arkanosis
  • 2,119
  • 1
  • 13
  • 18