Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional using local variables in templated method in D

Tags:

templates

d

I'm not sure I'm using the right terminology, but I'm trying to make something like this:

struct test_t {
  int x;
  void test()() if(x == 10) {
    printf("X is ten!\n");
  };
  void test()() {
    printf("X is not ten!\n");
  };
};

test_t test;
test.x = 10;
test.test(); // output: X is ten!

Is something like this possible? I won't use this in real world code, I was simply wondering if the language supports something like this.

like image 575
paulotorrens Avatar asked Jan 21 '14 18:01

paulotorrens


1 Answers

You can't do it with a run time value because templates are all figured out at compile time. You can do it with a compile time value though:

struct test_t(int x) {
   void test()() if(x == 10) {}
   // etc
}

test_t!(10) test;
test.test(); // X is ten

But notice that the compile time variable used there:

  • Is set when you define the type - a test_t!10 is not the same type as test_t!20
  • Cannot be changed
  • Can be used in static if, template constraints, static array sizes, or anywhere else you would use a number literal

A regular variable though would need to use a regular if, inside the method, to do any branching.

like image 114
Adam D. Ruppe Avatar answered Oct 11 '22 13:10

Adam D. Ruppe