Taking a constant reference to a constant/non const object

helxi brucewayneshit at gmail.com
Wed Nov 15 09:49:56 UTC 2017


On Wednesday, 15 November 2017 at 09:34:32 UTC, helxi wrote:
> On Wednesday, 15 November 2017 at 09:23:53 UTC, Jonathan M 
> Davis wrote:
>> On Wednesday, November 15, 2017 09:04:50 helxi via 
>> Digitalmars-d-learn wrote:
>>> Hi. What function signature should I use for receiving a 
>>> constant
>>> reference of an r/l value object? Is it auto fn(inout ref 
>>> const
>>> myClass obj)?
>>> I want to:
>>> 1. Take a constant reference of the object, not copy them
>>> 2. The object itself may be const or non const.
>>
>> ref const(Type) would be the const version of ref Type. e.g.
>>
>> auto foo(ref const(int) i) {...}
>>
>> - Jonathan M Davis
>
> Thanks. Just a couple of follow-ups:
> 1. I've never seen a signature like `const(int)`is the 
> enclosing parenthesis around the `int` necessary?
> 2. What effects does prefixing the arguments with `inout` have? 
> For example:  fn(inout ref const string str){...}

Terribly sorry for my bad choice of words. Basically I want to 
utilize D's "inout" to avoid writing two functions like this:

#include <iostream>
#include <string>

void fn(std::string& str) {
   std::cout << str << " called from fn(std::string& str)"
             << "\n ";
}

void fn(const std::string& str) {
   std::cout << str << " alled from fn(const std::string& str)"
             << "\n";
}

int main() {
   fn("Test 1");
   std::string b = "test";
   b += " 2";
   fn(b);
}



More information about the Digitalmars-d-learn mailing list