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;
		write("User Type: ");
	} else {
		write("Another Type: ");

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

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?

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