www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Compare type with another at CT

reply "Frustrated" <c1514843 drdrb.com> writes:
I am trying to compare a type with another type at compile time.

My code is

class Q(T)
{
	static auto foo()
	{
		static if (T is A)
		{
                      ...
		}
		static assert(0, "error");
	}
}

and get the error "cannot interpret A at compile time" on the
static if line.

A is an interface.

I simply want to determine if a type is derived from another type
at compile time.
Jan 23 2014
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
On Thursday, 23 January 2014 at 16:21:39 UTC, Frustrated wrote:
 		static if (T is A)
Try: static if(is(T : A)) {} The is() thingy is different than the is operator. T:A means "T implicitly converts to A", so if T is a class implementing interface A, that would pass. There's also is(T == A) if you want a more specific check, as well as IIRC 5 other forms of the is() thing which get weirder but all do a specific task.
Jan 23 2014
parent reply "Frustrated" <c1514843 drdrb.com> writes:
Yes, I that is what I tried initially but the error was  due to
that static if.

Not sure why

but

		static if (is(T : A))
		{
                       ...
		}
		static assert(0, "error");


doesn't work as the assert is called no matter what. Initially I
forgot to return the value after changing the code but that
doesn't matter.

Had to change it to


		static if (is(T : A))
		{
                       ...
                       return ...;
		} else
		   static assert(0, "error");
                  return null;

I guess because return is not "static" in some sense.
Jan 23 2014
parent "Stanislav Blinov" <stanislav.blinov gmail.com> writes:
On Thursday, 23 January 2014 at 16:40:49 UTC, Frustrated wrote:
 Yes, I that is what I tried initially but the error was  due to
 that static if.

 Not sure why

 but

 		static if (is(T : A))
 		{
                       ...
 		}
 		static assert(0, "error");


 doesn't work as the assert is called no matter what. Initially I
 forgot to return the value after changing the code but that
 doesn't matter.
As it should be. That static assert gets compiled unconditionally, thus asserts.
 Had to change it to


 		static if (is(T : A))
 		{
                       ...
                       return ...;
 		} else
 		   static assert(0, "error");
                  return null;

 I guess because return is not "static" in some sense.
else is the correct thing to do here. Otherwise you could have put a runtime assert(0) there, i.e.: static if (is(T : A)) { return "All is good"; } assert(0, "This should never happen!");
Jan 23 2014