开发者

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::cou开发者_StackOverflow中文版t << "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.


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() {}


There are no methods with name func() declared in class Y, so compiler can not find any Y::func() declaration

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜