mirror of
https://github.com/bspeice/speice.io
synced 2024-12-22 16:48:10 -05:00
Const-ness of method arguments as well
This commit is contained in:
parent
3709bcd0fd
commit
92f24c50ee
@ -111,15 +111,11 @@ public:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
# Require concept methods to take `const this`?
|
# Method Qualifiers
|
||||||
|
|
||||||
`std::is_const` should be able to handle it: https://en.cppreference.com/w/cpp/types/is_const
|
Rust allows declaring immutable, mutable, and consumed arguments (including `self`).
|
||||||
|
|
||||||
---
|
C++ can use `const_cast` to assert "constness" of `this` and method arguments:
|
||||||
|
|
||||||
`is_const` could be used to declare the class is const for an entire concept, but don't think you
|
|
||||||
could require const-ness for only certain methods. Can use `const_cast` to assert "constness"
|
|
||||||
though:
|
|
||||||
|
|
||||||
```c++
|
```c++
|
||||||
#include <concepts>
|
#include <concepts>
|
||||||
@ -128,6 +124,7 @@ though:
|
|||||||
template <typename T>
|
template <typename T>
|
||||||
concept ConstMethod = requires (T a) {
|
concept ConstMethod = requires (T a) {
|
||||||
{ const_cast<const T&>(a).method() } -> std::same_as<std::uint64_t>;
|
{ const_cast<const T&>(a).method() } -> std::same_as<std::uint64_t>;
|
||||||
|
{ a.another(std::declval<const std::uint64_t>()) } -> std::same_as<std::uint64_t>;
|
||||||
};
|
};
|
||||||
|
|
||||||
std::uint64_t my_function(ConstMethod auto a) {
|
std::uint64_t my_function(ConstMethod auto a) {
|
||||||
@ -139,6 +136,11 @@ public:
|
|||||||
std::uint64_t method() const {
|
std::uint64_t method() const {
|
||||||
return 42;
|
return 42;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NOTE: non-`const` value is also acceptable here.
|
||||||
|
std::uint64_t another(const std::uint64_t value) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
class WithoutConst {
|
class WithoutConst {
|
||||||
@ -146,6 +148,10 @@ public:
|
|||||||
std::uint64_t method() {
|
std::uint64_t method() {
|
||||||
return 42;
|
return 42;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::uint64_t another(const std::uint64_t value) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
@ -178,6 +184,9 @@ int main() {
|
|||||||
| ^~~~~~
|
| ^~~~~~
|
||||||
```
|
```
|
||||||
|
|
||||||
|
...but difficult to do anything beyond that. Is there a way to declare methods must be `noexcept`,
|
||||||
|
`volatile`, etc.? Also can't have methods that consume `this`.
|
||||||
|
|
||||||
# Implement methods on remote types
|
# Implement methods on remote types
|
||||||
|
|
||||||
Rust allows both arbitrary `self` and extension traits. Arbitrary self forms the basis of the
|
Rust allows both arbitrary `self` and extension traits. Arbitrary self forms the basis of the
|
||||||
|
Loading…
Reference in New Issue
Block a user