www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - C++ User-defined class qualifiers in D

reply Basile B. <b2.temp gmx.com> writes:
I've just read [this 
article](http://bannalia.blogspot.com/2023/08/user-defined-class-qua
ifiers-in-c23.html) about C++23 user defined typequals.

Thanks to `alias this` D can do the same since a long time and 
without new language feature:

```d
import std;

enum Qual;

template Qualified(Q,T)
{
      Q struct Qualified
     {
         T t;
         alias t this;
     }
}

struct S
{}

alias SQual = Qualified!(Qual,S);

void filterQual(T : S)(T t)
if (hasUDA!(T, Qual))
{}

void both(T : S)(T t)
{}

void main()
{
     S s;
     SQual sq;

     both(sq);
     both(s);
     filterQual(sq); // OK
     filterQual(s);  // NG
}
```

Not sure how (and if) the C++ version will gain more usability, 
however.
As note the author

 A more interesting challenge is the following: As laid out, 
 this technique implements syntactic qualifier subtyping, but 
 does not do anything towards enforcing the semantics associated 
 to each qualifier
Aug 19 2023
parent Tejas <notrealemail gmail.com> writes:
On Saturday, 19 August 2023 at 19:56:54 UTC, Basile B. wrote:

 As note the author

 A more interesting challenge is the following: As laid out, 
 this technique implements syntactic qualifier subtyping, but 
 does not do anything towards enforcing the semantics 
 associated to each qualifier
The only way to enforce semantics for `C++` and `D` would be via creating a compiler plugin that enforces the semantics, I think. The compiler can't perform the necessary semantics analysis if the logic for that is not present in it. The languages aren't even interpreted, such that the code to modify the behavior towards certain types/qualifiers could be presented on-the-fly and the interpreter/VM could adapt dynamically. One can write C++ plugins, atleast for clang, using https://clang.llvm.org/docs/Tooling.html#clang-plugins For D plugins, atleast for LDC, we most likely now have https://forum.dlang.org/post/clelngkqvihzybpxgldq forum.dlang.org
Aug 21 2023