如果基类构造函数不是constexpr,我可以构造派生类constexpr的构造函数吗?
我想从“设计模式”编译一个例子,我面临着以下问题:如果基类构造函数不是constexpr,我可以构造派生类constexpr的构造函数吗?
我有一个基类网站地图:
class MapSite{
public:
MapSite();
virtual ~MapSite();
virtual void Enter() = 0;
};
和派生类中房:
class Room : public MapSite final{
private:
unsigned int room_number;
public:
Room(unsigned int rn) : room_number(rn) {};
virtual void Enter() override;
};
从另一个类我要调用的函数
virtual std::unique_ptr<Room> MakeRoom(unsigned int n) {return make_unique<Room(n)>();}
当我这样做,我得到以下错误:
error: temporary of non-literal type ‘Room’ in a constant expression
virtual std::unique_ptr<Room> MakeRoom(unsigned int n) {return unique::make_unique<Room(n)>();}
所以我想这个问题可能是在构造函数必须是constexpr
为了从另一个函数调用间的构造函数,但构造函数设置:
constexpr Room(unsigned int rn) : room_number(rn) {};
会产生这样的错误:
error: call to non-constexpr function ‘MapSite::MapSite()’
constexpr Room(unsigned int rn) : room_number(rn) {};
我的基本问题是,我能否马ke是派生类构造函数constexpr,即使基类构造函数不是。或者,如果有更好的概念来解决这个问题。
PS:make_unique是一个C++ 14功能,我从这里How to implement make_unique function in C++11?为C++ 11,模拟其我与
Can i make the constructor of a derived class contexpr if the base class constructor is not constexpr?
不,你不能。
一个constexpr函数不能调用非constexpr函数。构造函数必须调用所有的子对象(包括基础子对象)的构造函数。因此,所有的子对象构造函数都必须是constexpr,否则完整的对象构造函数可能不会被constexpr。
这就是说,你原来的问题是分开的,并且由NathanOliver的答案覆盖。
这里的问题是编译不是Room
需要constexpr
构造函数,但你将值传递给期望类型的模板。在
virtual std::unique_ptr<Room> MakeRoom(unsigned int n) {return make_unique<Room(n)>();}
的Room(n)
部分尝试构建一个Room
,并用它作为make_unique
模板参数。这不是你想要做的。 make_unique
需要一个类型,因为它会根据传递给它的参数构造该类型的std::unique_ptr
。如果你想构建一个Room
与n
然后使用
virtual std::unique_ptr<Room> MakeRoom(unsigned int n) {return make_unique<Room>(n);}
问问自己:那些甚至试图在常量表达式中使用'Room'的代码是什么?为什么? – Barry