www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - confused about template constructors and implicit type conversions

reply NeeO <zelux gmx.us> writes:
Would someone be able to explain this ? I can only seem to call a 
template constructor in one way, but I can't seem to pass what 
looks like an accepted type to the template constructor via a 
function call.

/+ main.d +/
import std.stdio ;

struct obj_ (T) {
    int demo ;

    this (int R,int C)(T[R][C] val) {
       writeln ("init for type is ",val.init) ;
       writeln ("num rows         ",R       ) ;
       writeln ("num cols         ",C       ) ;
    }
}
void check (obj_!float val) {
    writeln ("success") ;
}

int main () {
    float[3][4] testval ;
    obj_!float  p = testval ; /+ works +/

    check (testval) ; /+ not callable using argument types 
compiler error +/
    return 0 ;
}
Dec 04 2019
parent Basile B. <b2.temp gmx.com> writes:
On Wednesday, 4 December 2019 at 23:53:53 UTC, NeeO wrote:
 Would someone be able to explain this ? I can only seem to call 
 a template constructor in one way, but I can't seem to pass 
 what looks like an accepted type to the template constructor 
 via a function call.

 /+ main.d +/
 import std.stdio ;

 struct obj_ (T) {
    int demo ;

    this (int R,int C)(T[R][C] val) {
       writeln ("init for type is ",val.init) ;
       writeln ("num rows         ",R       ) ;
       writeln ("num cols         ",C       ) ;
    }
 }
 void check (obj_!float val) {
    writeln ("success") ;
 }

 int main () {
    float[3][4] testval ;
    obj_!float  p = testval ; /+ works +/

    check (testval) ; /+ not callable using argument types 
 compiler error +/
    return 0 ;
 }
Hello, the problem you encounter here is that D, per spec, does not perform implicit construction from parameters. You have to constructs explicitly. Nothing more to explain.
Dec 04 2019