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
  • 25,930
  • 29
  • 122
  • 185
  • Did you read http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – VP. Jul 06 '15 at 15:28
  • 1
    Have you tried e.g. `template template void BaseTemplate::templateMethod(Policy& policy)`? Just like other templated functions? – Some programmer dude Jul 06 '15 at 15:29

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,229
  • 1
  • 12
  • 18