【发布时间】:2021-09-26 21:46:57
【问题描述】:
我想在类模板中使用模板化方法。我的意思是该方法的附加“模板化”。以下代码 sn -p 应该解释我想要实现的目标:
#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;
}
这行得通。但是,我想将someFunction 的定义移出类的主体(我有很多模板特化要编写,我不想弄乱类定义)。这是什么语法?
我知道如何在类体之外为模板化类定义方法,并且我知道如何在类体之外定义非模板类的模板化方法。现在我想同时进行。
【问题讨论】:
-
template <size_t SIZE> template <typename T> T SomeClass<SIZE>::someFunction(size_t position) { ...
标签: c++ templates template-classes