Const vs Non const method
Ola Fosheim Grøstad via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Mar 7 03:14:02 PST 2016
On Monday, 7 March 2016 at 10:52:53 UTC, Ola Fosheim Grøstad
wrote:
> On Sunday, 6 March 2016 at 17:53:47 UTC, Namespace wrote:
>> What would be the C++ way? Is there any comfortable way to
>> solve this problem in a nice way like D?
>
> C++ has a non-idiomatic language culture. There are many ways
> to do it. One clean way could be to use a templated method,
> another way is to use a function object, a dirty way would be
> to use a const-cast.
Another thing in C++ is that you can overload members on rvalue
and lvalue references, from
http://en.cppreference.com/w/cpp/language/member_functions :
#include <iostream>
struct S {
void f() & { std::cout << "lvalue\n"; }
void f() &&{ std::cout << "rvalue\n"; }
};
int main(){
S s;
s.f(); // prints "lvalue"
std::move(s).f(); // prints "rvalue"
S().f(); // prints "rvalue"
}
Of course, all of this is just because you don't get to specify
the type of the "this" pointer... So not as clean as it should
be, but that applies to both languages. Adding lots of syntax
with no real semantic benefits.
More information about the Digitalmars-d-learn
mailing list