www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Nested struct sauses error

reply fantom <lokomot476 mail.ru> writes:
I write simple function to get unique values in array of arrays 
with position

import std.stdio;
import std.range;
import std.algorithm;

struct Value {
	int var;
	size_t index;
	bool opEquals()(auto ref const Value rhs) const {
		return var==rhs.var;
	}
	int opCmp(ref const Value rhs) const {
		return var-rhs.var;
		
	}
}

auto get_unique(int[][] row) {
	auto unique=row.enumerate
		.map!(iv=>iv.value.map!(var=>Value(var, iv.index)))
		.join
		.sort()
		.group
		.filter!(t=>t[1]==1)
		.map!(t=>[t[0].var, t[0].index]);
	return unique;	
}
void main(){
	auto 
row=[[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]];
	get_unique(row).writeln;
}	

Output: [[1, 0], [9, 4]]

But when I move Value struct into function, I get compilation 
error

import std.stdio;
import std.range;
import std.algorithm;

auto get_unique(int[][] row) {
	struct Value {
		int var;
		size_t index;
		bool opEquals()(auto ref const Value rhs) const {
			return var==rhs.var;
		}
		int opCmp(ref const Value rhs) const {
			return var-rhs.var;
		}
	}

	auto unique=row.enumerate
		.map!(iv=>iv.value.map!(var=>Value(var, iv.index)))
		.join
		.sort()
		.group //here: Error: template instance 
std.algorithm.iteration.group!("a == b", SortedRange!(Value[], "a 
< b")) error instantiating
		.filter!(t=>t[1]==1)
		.map!(t=>[t[0].var, t[0].index]);
	return unique;	
}
void main(){
	auto 
row=[[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]];
	get_unique(row).writeln;
}	

dmd2/include/std/algorithm/iteration.d(1419): Error: field 
_current must be initialized in constructor, because it is nested 
struct
app.d(21): Error: template instance 
std.algorithm.iteration.group!("a == b", SortedRange!(Value[], "a 
< b")) error instantiating

Can anybody explain me what is wrong? Thanks
Mar 12 2017
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Sunday, 12 March 2017 at 18:46:14 UTC, fantom wrote:
 Can anybody explain me what is wrong? Thanks
easy fix is to likely make it a `static struct` even if nested. That will remove access to local variables of the function but should compile. The reason is that access to those local variables needs a hidden pointer that won't be initialized properly without the right construction.
Mar 12 2017
parent Era Scarecrow <rtcvb32 yahoo.com> writes:
On Sunday, 12 March 2017 at 18:59:43 UTC, Adam D. Ruppe wrote:
 The reason is that access to those local variables needs a 
 hidden pointer that won't be initialized properly without the 
 right construction.
While it's the most likely reason for the error; Shouldn't it detect it never used anything outside and not try to include the hidden pointer?
Mar 12 2017