Mar*_*cký 5 c++ constexpr c++17 if-constexpr
Is it possible to overload the operator new to be constexpr function? Something like:
constexpr void * operator new( std::size_t count );
Run Code Online (Sandbox Code Playgroud)
The reason why would be to execute constexpr function within the overloaded operator body where count argument value would be an input data... As the operator is invoked by:
SomeClass * foo = new SomeClass();
Run Code Online (Sandbox Code Playgroud)
The size of the data type is know at compile time, isn’t it? (count== sizeof(SomeClass)
) So the count can be considered as compile time constant?
constexpr void * operator new( std::size_t count )
{
if constexpr ( count >= 10 ) { /* do some compile-time business */ }
}
Run Code Online (Sandbox Code Playgroud)
Many thanks in advance to anyone willing to help!
您不能重载运算符new
to be constexpr
,主要问题归因于 C++ 标准指令\xc2\xa79.1.5/1constexpr
说明符 [dcl.constexpr](强调我的):
\n\n\n说明
\nconstexpr
符仅应用于变量或变量模板的定义或者函数或函数模板的声明。使用\n 说明符声明的函数或静态数据成员constexpr
隐式是内联函数或变量\n (9.1.6)。如果函数或函数模板的任何声明具有\nconstexpr
说明符,则其所有声明都应包含\nconstexpr
说明符。
也就是说,为了重载运算符,new
其之前的所有声明也必须是constexpr
,但它们不是,因此在constexpr
出现编译时错误时会重载它。
归档时间: |
|
查看次数: |
1584 次 |
最近记录: |