www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - opApply and const

reply "Arne Ludwig" <ludwig.arne gmail.com> writes:
Hello,

when using opApply it seems natural to have two versions: one 
normal and one const. My problem is that I cannot find a way to 
describe both versions with one code block. Since there could be 
a number of basic variants with different numbers of delegate 
arguments this can lead to serious code duplication.

This problem was discussed years ago:

http://www.digitalmars.com/d/archives/digitalmars/D/opApply_and_const_63436.html

Small example:

http://pastebin.com/kRrPp6Yg

In that example I need four times (mostly) the same code. There 
should be any way around that. Has someone ideas?
May 08 2014
parent "anonymous" <anonymous example.com> writes:
On Friday, 9 May 2014 at 05:26:12 UTC, Arne Ludwig wrote:
 Hello,

 when using opApply it seems natural to have two versions: one 
 normal and one const. My problem is that I cannot find a way to 
 describe both versions with one code block. Since there could 
 be a number of basic variants with different numbers of 
 delegate arguments this can lead to serious code duplication.

 This problem was discussed years ago:

 http://www.digitalmars.com/d/archives/digitalmars/D/opApply_and_const_63436.html

 Small example:

 http://pastebin.com/kRrPp6Yg

 In that example I need four times (mostly) the same code. There 
 should be any way around that. Has someone ideas?
I answered a similar question on stackoverflow [1]. The same approach can be used here. If dg doesn't mutate, the mutable overloads are de-facto const. So, if you have a const dg, it's safe to cast the object's const away and call the mutable versions of opApply: /* de-facto const if dg doesn't mutate */ int opApply(int delegate (T*) dg) { ... implementation ... } /* ditto */ int opApply(int delegate (size_t, T*) dg) { ... implementation ... } int opApply(int delegate(const T*) dg) const { return (cast() this).opApply(cast(int delegate(T*)) dg); } int opApply(int delegate (size_t, const T*) dg) const { return (cast() this).opApply(cast(int delegate(size_t, T*)) dg); } [1] http://stackoverflow.com/questions/22442031/how-to-make-a-template-function-const-if-the-template-is-true/22442425
May 09 2014