简体   繁体   中英

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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