I would like to use a templated method within a class template. I mean an additional "templatification" of the method. The following code snippet should explain what I want to achieve:
#include <iostream>
using namespace std;
// a class with a template parameter
template <size_t SIZE>
class SomeClass {
public:
static const size_t size = SIZE; // do something with template parameter SIZE
// declaration AND definition of some templated method within class body
template <typename T> T someFunction(size_t position) {
return static_cast<T>(position * size); // just do something with type T
}
};
int main () {
cout << "Access static information: SomeClass<15>::size = " << SomeClass<15>::size << endl;
SomeClass<10> someclass; // instantiate with template parameter 10
cout << "Access instance information: size = " << someclass.size << endl;
cout << "Use someFunction with float return value: someclass.SomeFunction<float>(13) = " << someclass.someFunction<float>(13) << endl;
return 0;
}
This works. However, I would like to move the definition of someFunction
out of the body of the class (I have a lot of template specializations to write and I don't want to clutter up the class definition). What is the syntax for this?
I know how to define methods for templated classes outside the class body and I know how to define a templated method of a non-template class outside the class body. Now I would like to to both at once.
You need two templates: One for the class and one for the function.
Like in:
template<size_t SIZE>
template <typename T>
T SomeClass<SIZE>::someFunction(size_t position) {
return static_cast<T>(position * size); // just do something with type T
}