Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

visual-c++

Is the following code legal C++?

MS Visual C++ fails, but gcc and clang are fine: https://godbolt.org/z/vsQOaW

It could be an msvc bug, but wanted to check first:

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();
}
like image 576
sly Avatar asked Dec 06 '25 07:12

sly


1 Answers

junk may get instantiated just like the rest of virtual functions because it is required to populate vtable. So all the compilers seem to demonstrate conforming behavior:

17.8.1 Implicit instantiation [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.

like image 57
user7860670 Avatar answered Dec 07 '25 21:12

user7860670



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!