From 92f24c50ee4a95e90e782c9a961f6905b42bd611 Mon Sep 17 00:00:00 2001 From: Bradlee Speice Date: Sat, 29 Aug 2020 21:49:17 -0400 Subject: [PATCH] Const-ness of method arguments as well --- _posts/2020-08-05-static-polymorphism.md | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/_posts/2020-08-05-static-polymorphism.md b/_posts/2020-08-05-static-polymorphism.md index 52ceb48..739c73d 100644 --- a/_posts/2020-08-05-static-polymorphism.md +++ b/_posts/2020-08-05-static-polymorphism.md @@ -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`). ---- - -`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++ can use `const_cast` to assert "constness" of `this` and method arguments: ```c++ #include @@ -128,6 +124,7 @@ though: template concept ConstMethod = requires (T a) { { const_cast(a).method() } -> std::same_as; + { a.another(std::declval()) } -> std::same_as; }; std::uint64_t my_function(ConstMethod auto a) { @@ -139,6 +136,11 @@ public: std::uint64_t method() const { return 42; } + + // NOTE: non-`const` value is also acceptable here. + std::uint64_t another(const std::uint64_t value) { + return value; + } }; class WithoutConst { @@ -146,6 +148,10 @@ public: std::uint64_t method() { return 42; } + + std::uint64_t another(const std::uint64_t value) { + return value; + } }; 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 Rust allows both arbitrary `self` and extension traits. Arbitrary self forms the basis of the