www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Can I make this work?

reply Jack <jckj33 gmail.com> writes:
there's a value passed as template parameter which is know at 
compile time (can be used with static if) but I don't know how 
can I pass it around and use in a property. Obviously enum 
deosn't work because it would be a local to the function. 
immutable would result in compiler can't read it at compile time. 
version doesn't work either because it isn't at module scope but 
a function.

full code:


struct S
{
	enum x = init!(false, 10);
	enum y = init!(true, 20);

	this(string s)
	{
		type = Type.type1;
	}

	this(int n)
	{
		type = Type.type2;
	}

	static auto init(bool v, int val)()
	{
		auto s = S();

		static if(v)
		{
			s.type = Type.type1;
		}
		else
		{
			s.type = Type.type2;
		}

		s.n = val;
		return s;
	}

	int value()
	{
		// would to use static if here or just
		// get rid of that check if type is Type.type1,
		// information which is available at init()
		// template function.
		if(type == Type.type2) {
			// do something
		}

		return n;
	}

	Type type;
	int n;
}

enum Type
{
	type1,
	type2,
	type3
}
Mar 19 2021
parent Kagamin <spam here.lot> writes:
struct S
{
	this(string s)
	{
		type = Type.type1;
	}

	this(int n)
	{
		type = Type.type2;
	}

	Type type;
	int n;
}

int value(S s)()
{
	static if(s.type == Type.type2) {
		// do something
	}

	return n;
}
Mar 20 2021