gpt4 book ai didi

c++ - 使用具有 C++20 概念的继承类从模板类继承

转载 作者:行者123 更新时间:2023-12-03 06:51:29 26 4
gpt4 key购买 nike

我正在尝试编写一个类似于 Ogre3Ds 的单例基类 Ogre::Singleton 使用 C++20 std::default_initializable .

#include <concepts>

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

class Foo: public Singleton<Foo> {};
此代码无法编译:
error C7602: 'Singleton': the associated constraints are not satisfied
我会期待吗?如果不是:为什么?
我正在使用最新的 MSVC 和 /std:c++latest .

最佳答案

之所以不能这样做,是因为在将 Foo 作为模板参数提供给 Singleton 时,它是一个不完整的类型,并且是 incomplete type根本不可初始化(所以它不能被默认初始化)
这是一个示例程序,它提供了一种更易于理解的错误:

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

struct B : A<B>{};
编译器错误 (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>
| ^

关于c++ - 使用具有 C++20 概念的继承类从模板类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64885823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com