I am trying to invoke a different hello_world
function based on the value of the int x
template parameter but same bye_world
function for any template parameter of int x
.
Here is what was attempted (bool enable
is used to try and achieve this):
// template_class.hpp
template <int x, int y, int z, bool enable> class TemplateClass {
public:
void hello_world();
void bye_world();
};
// template_class.cpp
#include <string>
#include <iostream>
using namespace std;
#include "template_class.hpp"
template <int x, int y, int z, bool enable> void TemplateClass<x, y, z, x == 1>::hello_world() {
std::cout << "hello world from 1" << endl;
}
template <int x, int y, int z, bool enable> void TemplateClass<x, y, z, x == 2>::hello_world() {
std::cout << "hello world from 2" << endl;
}
template <int x, int y, int z, bool enable> void TemplateClass<x, y, z, enable>::bye_world() {
std::cout << "bye world either from 1 or 2" << endl;
}
template class TemplateClass<1, 1, 1, true>;
template class TemplateClass<2, 2, 2, true>;
// main.cpp
#include <iostream>
#include "template_class.hpp"
#include <string>
int main() {
TemplateClass<1, 1, 1, true> *a = new TemplateClass<1, 1, 1, true>();
TemplateClass<2, 2, 2, true> *b = new TemplateClass<2, 2, 2, true>();
a->hello_world();
b->hello_world();
b->bye_world();
a->bye_world();
return 0;
}
compiler is not happy about this approach.
# g++ --std=c++11 main.cpp template_class.cpp -o run
template_class.cpp:6:82: error: nested name specifier 'TemplateClass<x, y, z, x == 1>::' for declaration does not refer into a class, class template or class template partial specialization
template <int x, int y, int z, bool enable> void TemplateClass<x, y, z, x == 1>::hello_world() {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
template_class.cpp:10:82: error: nested name specifier 'TemplateClass<x, y, z, x == 2>::' for declaration does not refer into a class, class template or class template partial specialization
template <int x, int y, int z, bool enable> void TemplateClass<x, y, z, x == 2>::hello_world() {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
2 errors generated.
Any ideas how to achieve this?