简体   繁体   English

类模板方法特化

[英]Class template method specialization

I'm trying to specialize a template method like this:我正在尝试专门化这样的模板方法:

template <typename X, typename Y>
class A {
public:
    void run(){};
};


template<typename Y>
void A<int, Y>::run() {}

But I get但我得到

main.cpp:70:17: error: nested name specifier 'A<int, Y>::' for declaration does not refer into a class, class template or class template partial specialization

I understand that the specialization isn't yet complete because I haven't instantiated it with a specific Y , but how can I do that?我知道专业化还没有完成,因为我还没有用特定的Y实例化它,但是我该怎么做呢?

You need at first partially specialize the class itself including the function declaration.您首先需要部分特化类本身,包括函数声明。 After that you can write its definition.之后,您可以编写其定义。 You may not partially specialize a function.您可能不会部分特化某个功能。

For example例如

#include <iostream>

template <typename X, typename Y>
class A {
public:
    void run()
    {
        std::cout << "How do you do?\n";
    };
};


template<typename Y>
class A<int, Y>
{
public:
    void run();
};

template<typename Y>
void A<int, Y>::run()
{
    std::cout << "Hello World!\n";
}

int main() 
{
    A<int, int>().run();
    A<double, int>().run();
    
    return 0;
}

The program output.程序输出。

Hello World!
How do you do?

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

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