digitalmars.D.learn - Anyone has links to useful short-snippets of trait pattern examples?
- frame (25/25) Dec 18 2020 The manual often doesn't show the full potential of traits on the
The manual often doesn't show the full potential of traits on the first sight or what they are really good for. But there are also all-day scenarios where I would just be happy for a quick lookup. For example, to assign a value to a class property which may have setter-overloads, I'm using a pattern like this: void Foo(T, string property)(Variant data, T object) { static if(!isSomeFunction!(__traits(getMember, T, property))) { __traits(getMember, object, property) = data.get!(typeof(__traits(getMember, object, property))); } else { foreach(ov; __traits(getOverloads, T, property)) { static if((Parameters!ov).length == 1) { __traits(getMember, object, property) = data.get!(Parameters!ov[0]); } } } } Somebody already may have a better implementation and of course it depends on your code - but it shows how to use it. The part with the overloads is also important here because without it the compiler would complain about "functions cannot return function" or similiar errors and you would think __traits(getMember) could not handle that.
Dec 18 2020