www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - template auto deduction

reply Alex <sascha.orlov gmail.com> writes:
Hey, template gurus :)

given this:

struct M(alias I : S!E, alias S, E...)
{
	R!E r;
	this(S)(S initStruct)    // line 4
	{
		r = R!E(initStruct);
	}
}
struct R(E...)
{
	this(S)(S initStruct)    // line 12
	{
		// do some cool stuff
	}
}
void main()
{
	FS!(Etype1) fs;
	auto m = M!(typeof(fs))(fs);    // line 21.
	auto a = M!(fs); // does not work
	auto b = M(fs); // does not work	
}
struct FS(T...){}
struct Etype1{}

Everything works as expected, especially line 21. The question is 
about syntactic sugar: What I have to change, to use auto 
deduction and to create the M struct like in line 22 or 23?

By the way, I'm aware, that the type matching in lines 4 and 12 
is lost, in the way it is written here. However, it is meant to 
exist, if this helps in some way...

Thanks a lot in advance
Alex
Oct 06
parent reply Steven Schveighoffer <schveiguy yahoo.com> writes:
On 10/6/17 5:08 PM, Alex wrote:
 Hey, template gurus :)
 
 given this:
 
 struct M(alias I : S!E, alias S, E...)
 {
      R!E r;
      this(S)(S initStruct)    // line 4
      {
          r = R!E(initStruct);
      }
 }
 struct R(E...)
 {
      this(S)(S initStruct)    // line 12
      {
          // do some cool stuff
      }
 }
 void main()
 {
      FS!(Etype1) fs;
      auto m = M!(typeof(fs))(fs);    // line 21.
      auto a = M!(fs); // does not work
      auto b = M(fs); // does not work
 }
 struct FS(T...){}
 struct Etype1{}
 
 Everything works as expected, especially line 21. The question is about 
 syntactic sugar: What I have to change, to use auto deduction and to 
 create the M struct like in line 22 or 23?
 
 By the way, I'm aware, that the type matching in lines 4 and 12 is lost, 
 in the way it is written here. However, it is meant to exist, if this 
 helps in some way...
 
 Thanks a lot in advance
 Alex
What you need is IFTI or "Implicit Function Template Instantiation" Note the "Function" part of it, in that it's only valid for functions. So you need a factory function: auto m(T)(T x) { return M!(T)(x); } ... auto b = m(fs); // ok There is an enhancement request to make constructors have the same mechanism. Not sure if or when it would be implemented. -Steve
Oct 06
parent Alex <sascha.orlov gmail.com> writes:
On Friday, 6 October 2017 at 21:42:40 UTC, Steven Schveighoffer 
wrote:
 What you need is IFTI or "Implicit Function Template 
 Instantiation"

 Note the "Function" part of it, in that it's only valid for 
 functions.

 So you need a factory function:

 auto m(T)(T x)
 {
   return M!(T)(x);
 }

 ...

 auto b = m(fs); // ok

 There is an enhancement request to make constructors have the 
 same mechanism. Not sure if or when it would be implemented.

 -Steve
Ha! Yes :) Thanks a lot :) That's what is meant by convenience methods inside the library, sometimes...
Oct 06