www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Problem with type cast in if condition

reply NiRu <nruzycki gmail.com> writes:
Hi there,

I have a problem with the typecast within my if condition, the 
dmd2 compiler says he can not cast int to User, but it never 
reaches an int type the condition (at most, the else branch).

my try:

struct User {
	string name;
}

void printName(T)(T value)
{
	if(is(typeof(value) == User)){
		User u = cast(User) value;
		writeln(u.name);
		
		write("User Type: ");
		writeln(value);
	} else {
		write("Another Type: ");
		writeln(value);
	}
	
}

void main(string[] args)
{
	User person;
	person.name = "Jacub";
	
	printName(362);
	printName("have a nice day");
	printName(person);
}



without the type cast line I have the following output:


Another Type: 362
Another Type: have a nice day
User Type: User("Jacub")


Instead with type cast "Error: cannot cast expression value of 
type int to User"

where is the problem?

Thanks!
Oct 06 2015
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Tuesday, 6 October 2015 at 20:35:28 UTC, NiRu wrote:
 	if(is(typeof(value) == User)){
Use `static if` instead of plain `if` here. Regular if does a runtime branch, so both true and else branches must compile with the same types. Static if does a compile time branch, allowing different code to be compiled based on the condition - meaning types can change too.
Oct 06 2015