微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么C显式实例化的模板方法不能覆盖虚方法?

为什么以下代码中的TemplateChild不起作用?我知道虚方法不能是模板,但为什么显式实例化模板方法不能覆盖虚方法
#include <iostream>

class VirtBase
{
public:
    VirtBase() {};
    virtual ~VirtBase() {};

    virtual void method( int input ) = 0;
    virtual void method( float input ) = 0;
};

class RegularChild : public VirtBase
{
public:
    RegularChild() {};
    ~RegularChild() {};

    void method( int input ) {
        std::cout << "R" << input << std::endl;
    }
    void method( float input ) {
        std::cout << "R" << input << std::endl;
    }
};

class TemplateBounceChild : public VirtBase
{
public:
    TemplateBounceChild() {};
    ~TemplateBounceChild() {};

    void method( int input ) {
        this->method<>( input );
    }
    void method( float input ) {
        this->method<>( input );
    }
    template< typename INPUT >
    void method( INPUT input ) {
        std::cout << "B" << input << std::endl;
    };
};

class TemplateChild : public VirtBase
{
public:
    TemplateChild() {};
    ~TemplateChild() {};

    template< typename INPUT >
    void method( INPUT input ) {
        std::cout << "T" << input << std::endl;
    };
};

template void TemplateChild::method< int >( int );
template void TemplateChild::method< float >( float );

int main( int,char**,char** )
{
    int i = 1;
    float f = 2.5f;

    VirtBase * v;

    RegularChild r;
    v = &r;

    r.method( i );
    r.method( f );
    v->method( i );
    v->method( f );

    TemplateChild c; // TemplateBounceChild here works correctly.
    v = &c;

    c.method( i );
    c.method( f );
    v->method( i );
    v->method( f );

    return 0;
}

gcc 4.4.7(CentOS 6)和Clang 3.3(主干177401)同意这两个纯虚方法没有在TemplateChild中实现,尽管在编译时这一点,TemplateChild显式地有一个名为’method’的方法,它接受一个浮点数,并且一个名为’method’的方法,它接受一个int.

是不是因为显式实例化已经来不及将TemplateChild视为非纯虚拟?

编辑:C 11 14.5.2 [temp.mem] / 4表示专业化不允许这样做.但是我在[temp.explicit]部分找不到同样清楚的东西.

4 A specialization of a member function template does not override a virtual function from a base class.

我还编辑了TemplateBounceChild以匹配C 11草案该部分中使用的示例.

解决方法

因为标准说的如此.见C 11 14.5.2 [temp.mem] / 3:

A member function template shall not be virtual.

原文地址:https://www.jb51.cc/c/117639.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐