constexpr 和 function body = delete:目的是什么?
constexpr and function body = delete: what's the purpose?
The definition of a constexpr function shall satisfy the following requirements:
[...]
- its function-body shall be = delete, = default, or [...]
这意味着以下 class 片段有效:
struct S {
constexpr void f() = delete;
};
删除 constexpr
函数的目的是什么?
定义它有什么好处 constexpr
如果有的话?
我想不出任何原因,但事实是在标准中允许它比禁止它更容易。
我想目的与任何 =delete
:
相同
如果您继承自 class,但不希望该函数在子classes 中可用。
例如:
class P{
public:
constexpr int foo(){return 42;}
};
class C : public P{
public:
constexpr int foo() = delete; //(*)
};
int main() {
P p;
cout << p.foo(); //ok
C c;
cout << c.foo(); //Compiler error only if line (*) is present.
return 0;
}
虽然我现在不能告诉你它在哪里有用 - 但我现在也看不出有任何理由禁止它。
这是基于 CWG 1199。丹尼尔·克鲁格勒写道:
it could be useful to allow this form in a case where a single piece of code is used in multiple configurations, in some of which the function is constexpr
and others deleted; having to update all declarations of the function to remove the constexpr specifier is unnecessarily onerous.
The definition of a constexpr function shall satisfy the following requirements:
[...]
- its function-body shall be = delete, = default, or [...]
这意味着以下 class 片段有效:
struct S {
constexpr void f() = delete;
};
删除 constexpr
函数的目的是什么?
定义它有什么好处 constexpr
如果有的话?
我想不出任何原因,但事实是在标准中允许它比禁止它更容易。
我想目的与任何 =delete
:
如果您继承自 class,但不希望该函数在子classes 中可用。
例如:
class P{
public:
constexpr int foo(){return 42;}
};
class C : public P{
public:
constexpr int foo() = delete; //(*)
};
int main() {
P p;
cout << p.foo(); //ok
C c;
cout << c.foo(); //Compiler error only if line (*) is present.
return 0;
}
虽然我现在不能告诉你它在哪里有用 - 但我现在也看不出有任何理由禁止它。
这是基于 CWG 1199。丹尼尔·克鲁格勒写道:
it could be useful to allow this form in a case where a single piece of code is used in multiple configurations, in some of which the function is
constexpr
and others deleted; having to update all declarations of the function to remove the constexpr specifier is unnecessarily onerous.