简体   繁体   English

如何专门化类模板的静态功能?

[英]How to specialize a static function of a class template?

When I tried to write something like this: 当我尝试写这样的东西时:

#include <iostream>

template <class T>
class A
{
public:
    static void doit();
};

template <>
static void A<int>::doit() 
{
    std::cout << "int" << std::endl;
}

template <>
static void A<double>::doit()
{
    std::cout << "double" << std::endl;
}

int main()
{
    A<int>::doit();
    A<double>::doit();
}

I got a compile error: 我收到一个编译错误: 错误消息的捕获

Specializing the whole class is ok. 全班专业都可以。 I just want to know is there any way to specialize only the static function? 我只想知道有什么方法可以专门化静态函数?

You should specify static keyword only once, in declaration. 在声明中,您只能指定一次static关键字。

Try this: 尝试这个:

template<>
void A<int>::doit() 
{
    std::cout << "int" << std::endl;
}

template<>
void A<double>::doit()
{
    std::cout << "double" << std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM