简体   繁体   中英

Problem with template specialisation for a derived class

When I compile the following

#include <iostream>

#define XXX 1
#define YYY 2

class X
{
public:

    template< int FLD >
    void func();
};

template<> void X::func< XXX >()
{
    std::cout << "X::func< " << XXX << " >" << std::endl;
}

class Y : public X
{
public:
};

template<> void Y::func< YYY >()
{
    std::cout << "Y::func< " << YYY << " >" << std::endl;
}

template<> void Y::func< XXX >()
{
    std::cout << "Y::func< " << XXX << " >" << std::endl;
}

int main( int c, char *v[] )
{
    X x;

    Y y;
}

I get

x.cpp:24: error: template-id 'func<2>' for 'void Y::func()' does not match any template declaration
x.cpp:24: error: invalid function declaration
x.cpp:29: error: template-id 'func<1>' for 'void Y::func()' does not match any template declaration
x.cpp:29: error: invalid function declaration

I'm trying to specialise a template in a base class.

Can anyone explain either how it's done or why I can't do it.

Thx Mark.

在类Y中没有声明名称为func()的方法,因此编译器找不到任何Y :: func()声明

You cannot do it, as you cannot do the following either and for the same reason, Y::func is not declared in Y :

class X {
public: 
   void foo();
};
void X::foo() {}
class Y : public X {
};
void Y::foo() {}

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