Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting from a template class using the inheriting class with C++20 concepts

I'm trying to write a Singleton base class similar to Ogre3Ds Ogre::Singleton using C++20's std::default_initializable.

#include <concepts>

template <std::default_initializable T>
struct Singleton {};

class Foo: public Singleton<Foo> {};

This code does not compile:

error C7602: 'Singleton': the associated constraints are not satisfied

Would I expect it to? If not: Why?

I'm using the latest MSVC with /std:c++latest.

like image 901
Frederic Schönberger Avatar asked Jan 25 '23 14:01

Frederic Schönberger


1 Answers

The reason why you can't do this is because at the point where Foo is given as a template parameter to Singleton, it is an incomplete type, and an incomplete type is not initializable at all (so it can not be default-initialized)

Here is a sample program that give a way more understandable error:

template<typename T>
struct A
{
    T value{};
};

struct B : A<B>{};

Compiler error (GCC 10.2)

<source>:5:7: error: 'A<T>::value' has incomplete type
    5 |     T value{};
      |       ^~~~~
<source>:8:8: note: forward declaration of 'struct B'
    8 | struct B : A<B>
      |        ^
like image 94
Alairion Avatar answered Jan 30 '23 01:01

Alairion