0

I am trying to make a class template with two arguments. Then I want to have the functions to be specialized.

template<class T, int number>
class TestClass{
public:
    TestClass(T x){
        a = x;
        z=number;
    };

    T print();

private:
    T a;
    int z;
};

template<class T, int number>
T TestClass<T, number>::print(){
    return a + number;
};

//This is the funktion I dont know how to handle
template<>
char TestClass<char, number>::print(){
    return a;
};
include <iostream>
include "TestClass.h"

using namespace std;

int main(){

    TestClass<int, 10> obj1(10);
    TestClass<double, 20> obj2(20.20);
    TestClass<char, 30> obj3('A');

    cout << obj1.print() << endl;
    cout << obj2.print() << endl;
    cout << obj3.print() << endl;
}

I know that this test program is not doing anything useful. char is just one example. It should be able to be anything.

Is this possible? Do I need another class template?

Many thanks in advance for answers

Jarod42
  • 203,559
  • 14
  • 181
  • 302
GorAhl
  • 61
  • 7
  • 1
    What should the `number` in `TestClass` be? It wasn't declared anywhere. – LogicStuff Feb 25 '16 at 12:55
  • 1
    afaik, you can not partially specialize just one function of class. But you can fully specialize class for specific parameters. – user2807083 Feb 25 '16 at 12:57
  • Possible duplicate of [C++ template, static function specialization](http://stackoverflow.com/questions/35610939/c-template-static-function-specialization) – Weak to Enuma Elish Feb 25 '16 at 12:57
  • 1
    If you want partial specialization of only a single member function, you need to turn it into a templated member function. – Some programmer dude Feb 25 '16 at 12:58
  • This is remarkably similar to that question I wrote an answer for earlier, so that's what came to mind as a dupe. I'm positive this is something there are probably many dupe targets for, though. – Weak to Enuma Elish Feb 25 '16 at 12:59
  • This is just a test to show what I mean. number in Test Class will do things in my "real" code. It's really not meant to use char either.. – GorAhl Feb 25 '16 at 17:28

0 Answers0