www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Using enum types

reply helxi <brucewayneshit gmail.com> writes:
Why can't enums be used as types in this (simplified) example?

enum Positivity
{
	Positive,
	Negative
}

struct Wave
{
public:
	Positivity slope;
}

enum Waves
{
	Sin = Wave(Positivity.Positive),
	Cos = Wave(Positivity.Negative)
}

int nth_value(T : Waves)(int n);

int nth_value(T : Waves.Sin)(int n)
{
	return n % 2 ? 1 : -1;
}

int nth_value(T : Waves.Cos)(int n)
{
	return n % 2 ? -1 : 1;
}

void main()
{
	import std.stdio;

	writeln(nth_value!(Waves.Sin)(1));
}
Dec 04 2017
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Monday, 4 December 2017 at 22:34:41 UTC, helxi wrote:
 enum Waves
 {
 	Sin = Wave(Positivity.Positive),
 	Cos = Wave(Positivity.Negative)
 }
 	writeln(nth_value!(Waves.Sin)(1));
 }
Sin and Cos there are actually values, not types...
Dec 04 2017
prev sibling parent Meta <jared771 gmail.com> writes:
On Monday, 4 December 2017 at 22:34:41 UTC, helxi wrote:
 Why can't enums be used as types in this (simplified) example?

 enum Positivity
 {
 	Positive,
 	Negative
 }

 struct Wave
 {
 public:
 	Positivity slope;
 }

 enum Waves
 {
 	Sin = Wave(Positivity.Positive),
 	Cos = Wave(Positivity.Negative)
 }

 int nth_value(T : Waves)(int n);

 int nth_value(T : Waves.Sin)(int n)
 {
 	return n % 2 ? 1 : -1;
 }

 int nth_value(T : Waves.Cos)(int n)
 {
 	return n % 2 ? -1 : 1;
 }
We Adam said, Waves.Sin and Waves.Cos are values, while Waves itself is the type. You want to do the following: int nth_value(Waves w: Waves.Sin)(int n) { //Etc. } At least I *think* that's what you want. I'm on mobile and dpaste is down so I have no way to double check the syntax, which I can never remember.
Dec 04 2017