www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - About variant

reply "bioinfornatics" <bioinfornatics fedoraproject.org> writes:
Dear that do a lot time wehere I not used std.variant. i would 
like to hide extra cast from user by using a generic ctor

import std.variant;

struct Alpha {
	Variant something;
	
	this(T)(T v){
		something = cast(Variant)v;
	}
	
}

void main(){
	auto a = Alpha!(int)( 6);
	auto b = Alpha!(string)( "hello");
	auto l = new Alpha[](2);
	l[0] = a;
	l[1] = b;
}

but that do not works.

Someone know a trick?

thanks
Jan 27 2015
next sibling parent "bioinfornatics" <bioinfornatics fedoraproject.org> writes:
I can do this
import std.variant;

struct Alpha {
	Variant something;
	
	this(Variant v){
		something = v;
	}
	
	static Alpha build(T)(T v){
		return Alpha( cast(Variant)v );
	}
	
}

void main(){
	auto a = Alpha.build!(int)( 6);
	auto b = Alpha.build!(string)( "hello");
	auto l = new Alpha[](2);
	l[0] = a;
	l[1] = b;
}

If someone has better
Jan 27 2015
prev sibling parent reply Justin Whear <justin economicmodeling.com> writes:
On Tue, 27 Jan 2015 20:46:59 +0000, bioinfornatics wrote:

 void main(){
 	auto a = Alpha!(int)( 6);
 	auto b = Alpha!(string)( "hello");
The Alpha struct is not a template, only the constructor is. Remove the explicit instantiations and IFTI does the work:
 void main(){
 	auto a = Alpha( 6);
 	auto b = Alpha( "hello");
Jan 27 2015
parent reply "bioinfornatics" <bioinfornatics fedoraproject.org> writes:
On Tuesday, 27 January 2015 at 21:00:16 UTC, Justin Whear wrote:
 On Tue, 27 Jan 2015 20:46:59 +0000, bioinfornatics wrote:

 void main(){
 	auto a = Alpha!(int)( 6);
 	auto b = Alpha!(string)( "hello");
The Alpha struct is not a template, only the constructor is. Remove the explicit instantiations and IFTI does the work:
 void main(){
 	auto a = Alpha( 6);
 	auto b = Alpha( "hello");
Oh really cool
Jan 27 2015
parent ketmar <ketmar ketmar.no-ip.org> writes:
On Tue, 27 Jan 2015 21:55:37 +0000, bioinfornatics wrote:

 On Tuesday, 27 January 2015 at 21:00:16 UTC, Justin Whear wrote:
 On Tue, 27 Jan 2015 20:46:59 +0000, bioinfornatics wrote:

 void main(){
 	auto a =3D Alpha!(int)( 6);
 	auto b =3D Alpha!(string)( "hello");
The Alpha struct is not a template, only the constructor is. Remove the explicit instantiations and IFTI does the work:
 void main(){
 	auto a =3D Alpha( 6);
 	auto b =3D Alpha( "hello");
=20 Oh really cool
or this: import std.variant; struct Alpha { Variant something; this(T) (T v) { something =3D cast(Variant)v; } } void main () { Alpha a =3D 6; Alpha b =3D "hello"; } =
Jan 27 2015