www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Should getSymbolsByUDA work with member variables?

reply cc <cc nevernet.com> writes:
This compiles:

class Foo {
	int x;
	 (1) void y() {}
	this() {
		static foreach (idx, field; getSymbolsByUDA!(Foo, 1)) {
		}
	}
}

This does not:

class Foo {
	 (1) int x;
	void y() {}
	this() {
		static foreach (idx, field; getSymbolsByUDA!(Foo, 1)) {
		}
	}
}

Error: value of `this` is not known at compile time

Is there an equivalent for getSymbolsByUDA for member variables, 
or is this a bug?
Feb 28 2020
next sibling parent Basile B. <b2.temp gmx.com> writes:
On Friday, 28 February 2020 at 18:34:08 UTC, cc wrote:
 This compiles:

 class Foo {
 	int x;
 	 (1) void y() {}
 	this() {
 		static foreach (idx, field; getSymbolsByUDA!(Foo, 1)) {
 		}
 	}
 }

 This does not:

 class Foo {
 	 (1) int x;
 	void y() {}
 	this() {
 		static foreach (idx, field; getSymbolsByUDA!(Foo, 1)) {
 		}
 	}
 }

 Error: value of `this` is not known at compile time

 Is there an equivalent for getSymbolsByUDA for member 
 variables, or is this a bug?
I dont see a bug, the error message is correct. I'd say that you have two options: 1. drop the `static` before `foreach`, for example to use the symbols during run-time 2. to do metaprog adopt another style of loop, e.g class Foo { (1) int x; void y() {} this() { alias AtOne = getSymbolsByUDA!(Foo, 1); static foreach (i; 0 .. AtOne.length) { pragma(msg, __traits(identifier, AtOne[i])); } } }
Feb 28 2020
prev sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 2/28/20 1:34 PM, cc wrote:
 This compiles:
 
 class Foo {
      int x;
       (1) void y() {}
      this() {
          static foreach (idx, field; getSymbolsByUDA!(Foo, 1)) {
          }
      }
 }
 
 This does not:
 
 class Foo {
       (1) int x;
      void y() {}
      this() {
          static foreach (idx, field; getSymbolsByUDA!(Foo, 1)) {
          }
      }
 }
 
 Error: value of `this` is not known at compile time
 
 Is there an equivalent for getSymbolsByUDA for member variables, or is 
 this a bug?
It does work. What doesn't work is using the symbol or aliasing it inside a member function. class Foo { (1) int x; void y() {} this() { } } static foreach(sym; getSymbolsByUDA!(Foo, 1)) pragma(msg, sym.stringof); // prints x But using foreach (not static) works inside the function. I'm not sure of the difference. I think it's confused because the symbols link to a real item inside a member, whereas they are just symbols outside. So it might think you want the instance member, which can't be accessed at compile time? But I don't know why. You should file a bug and see what is said about it. The fact that foreach on such a tuple works but static foreach doesn't is telling. -Steve
Feb 29 2020