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
.
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>
| ^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With