www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Structs as template parameters: weird error message

reply "biozic" <dransic gmail.com> writes:
The code below doesn't compile. Why this error message?
---
struct Item {
     int i;
}

struct Params {
     Item* item;

     this(int i) {
         item = new Item(i);  // line 9
     }
}

struct Foo(Params params) {}

enum foo = Foo!(Params(1));
---

test.d(9): Error: Item(1) is not an lvalue
Apr 02 2015
parent "Nicholas Wilson" <iamthewilsonator hotmail.com> writes:
On Thursday, 2 April 2015 at 23:12:25 UTC, biozic wrote:
 The code below doesn't compile. Why this error message?
 ---
 struct Item {
     int i;
 }

 struct Params {
     Item* item;

     this(int i) {
         item = new Item(i);  // line 9
     }
 }

 struct Foo(Params params) {}

 enum foo = Foo!(Params(1));
 ---

 test.d(9): Error: Item(1) is not an lvalue
this doesn't work because struct Foo is parameterised by in instance of Params. (like if you were implementing a fixed size array: struct FixedSizeArray(size_t len) {...}. here FixedSizeArray is parameterised by in instance of a size_t). Item is a pointer in Params and thus if it were to compile the compiler would need to know the value returned by `new`at compile time. There are two ways to get that to compile change `Item* item;` to `Item item;` or change `item = new Item(1);` to `item = null;` tl;dr you can't have r-value (pointers) in instance template parameter lists. i.e. struct foo(my_reference_type_or_type_containg_pointers instance) { ... }
Apr 02 2015