简体   繁体   English

模板类方法实例化当基类中的虚拟无关方法导致MSVC上的编译失败时

[英]template class method instantiation when a virtual unrelated method in the base class causes compilation failure on MSVC

Is the following code legal C++? 以下代码是否合法C ++?

MS Visual C++ fails, but gcc and clang are fine: https://godbolt.org/z/vsQOaW MS Visual C ++失败了,但gcc和clang很好: https//godbolt.org/z/vsQOaW

It could be an msvc bug, but wanted to check first: 它可能是一个msvc错误,但想先检查一下:

struct Base {
    virtual void junk() = 0;
};

template <class T>
struct Derived : Base {

    void junk() override {
        T::junkImpl();
    }

    void otherMethod() {
    }
};


template <class T>
struct NotDerived {

    void junk() {
        T::junkImpl();
    }

    void otherMethod() {
    }
};


struct TypeWithJunk {
    void junkImpl() {
    }
};

struct TypeWithoutJunk {};


void reproduce(NotDerived<TypeWithoutJunk>* ndt, Derived<TypeWithoutJunk>* dt) {

    // works - junk is not used, not instantiated
    ndt->otherMethod();

    // fails on MSVC - junk is instantiated even if not used
    dt->otherMethod();
}

junk may get instantiated just like the rest of virtual functions because it is required to populate vtable. junk可能像其他虚函数一样被实例化,因为它需要填充vtable。 So all the compilers seem to demonstrate conforming behavior: 因此,所有编译器似乎都表现出一致的行为:

17.8.1 Implicit instantiation [temp.inst] 17.8.1隐式实例化[temp.inst]

9 … It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated. 9 ...如果虚拟成员函数不会被实例化,则实现是否隐式实例化类模板的虚拟成员函数是未指定的。

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

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