This doesn't work in D:
void doSomething(auto a, auto b){
// ...
}
I'm just curious, will this ever work? Or is this just technically impossible? (Or just plain stupid?)
In anyway, can this be accomplished in any other way? I suppose I could use the ...
and look through the argument list, but I'm kinda making a library for lazy newbie people and want them to be able to create functions easily without really caring about data types. I'm playing with the idea of creating a struct called var
like
struct var{
byte type;
void* data
// ...
}
// and overload like all operators so that a lazy devver can do
var doSomething(var a, var b){
if(a == "hello")
b = 8;
var c = "No.:" ~ b ~ " says:" ~ a;
return c;
}
But my head is already starting to hurt right there. And, I'm kinda feeling I'm missing something. I'm also painfully aware that this is probably what templates are for... Are they? From the little I know, a template would look like this (?)
void doSomething(T, U)( T a, U b){
// ...
}
But now it doesn't look so clean anymore. Maybe I'm getting all this backwards. Maybe my confusion stems from my belief that auto
is a dynamic type, comparable to var
i javascript, but when in reality, it's something else?
And if it isn't a dynamic type, and this is probably a whole other topic, is it possible to create one? Or is there maybe even an open source lib available? A liblazy maybe?
(PS. Yeah, maybe the lazy devver is me : )
The auto keyword can not only be used as the return type for functions but also as the data type of the parameters declared in the function.
To use the auto keyword, use it instead of a type to declare a variable, and specify an initialization expression. In addition, you can modify the auto keyword by using specifiers and declarators such as const , volatile , pointer ( * ), reference ( & ), and rvalue reference ( && ).
1) auto keyword: The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In the case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.
Starting C++17 , you can use auto and decltype(auto) to declare non-type template parameters. This new feature provides a way to write generic code for non-type parameters of different types.
If doSomething
is generic over any type of a
and b
, then the template version is the right thing to do:
void doSomething(T, U)(T a, U b) {
// etc.
}
The compiler will detect the types represented by T
and U
at compile time and generate the proper code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With