Code compiles with g++ but not clang++ if incomplete type is used in templated function

Viewed 43
#include <variant>

struct A;
struct B;

using C = std::variant<A, B>;

struct A
{
  template <size_t n>
  void fun()
  {
    C c;
  }
};

The code I have posted compiles with g++, but not clang++. both using -std=c++17. I am not sure which one is expected, but was hoping I could get an explanation for why this happens, and if it's something that g++ specifications promise to always do, or if it's UB.

My guess is that g++ compiles various components in a different order. Templates might not be instantiated at all until they are used. But why does clang++ see the error then?

1 Answers

Apparently http://eel.is/c++draft/temp.res#8 has an explanation saying the program is ill-formed if "a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter".

Now I am wondering if g++ has a feature to make this work anyway, or if it's not something I can rely on.

Related