[英]How to define a templated method of a class template outside of class body
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).但是,我想将
someFunction
的定义移出类的主体(我有很多模板专业要编写,我不想弄乱类定义)。 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.