问题描述
我的模板出现语法错误
我想对模板类的静态函数进行部分专业化处理
I would like to partial specialize a static function of my template class
template <typename Foo, size_t bar = 26>
class MyClass
{
MyClass();
static void function();
};
#include "class.tpp"
class.tpp
template <typename Foo, bar>
MyClass<Foo, bar>::MyClass()
{ }
template <typename Foo>
inline
void
MyClass<Foo, 6>::function()
{
// ...
}
template <typename Foo>
inline
void
MyClass<Foo, 26>::function()
{
// ...
}
error: template definition of non-template
我只想为bar == 26和bar == 6实施MyClass<Foo, bar>::function
I just want to implement MyClass<Foo, bar>::function
for bar == 26 and bar == 6
如何正确执行此操作?谢谢
How to do that properly ?Thanks
推荐答案
该函数本身不是模板,它仅位于类模板中.您可以为这些情况专门设置类,但不能专门提供函数本身.
The function is not a template itself, it is only inside a class template. You can specialize the class for those cases, but not the function itself.
template <class Foo>
class MyClass<Foo, 26>
{
static void function() { ... }
};
假设您已经像这样专门化了类,则只能在类内部声明函数,然后在外部进行定义,如下所示:
Provided you have specialized the class like so, you can only declare the function inside the class, and define it outside like so:
template <class Foo>
void MyClass<Foo, 26>::function() { ... }
如果您事先不专门研究它,则会因使用不完整的类型而出现编译错误.
If you don't specialize it beforehand, you'll get a compilation error for using an incomplete type.
您可能还会发现此问题和有关专门化单个功能的问题的答案.在相关的类模板中.
You might also find this question and answer on specializing a single function inside a class template relevant.
这篇关于C ++模板,静态函数专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!