cross_module function overloading & alias & template: how to ?
Picaud Vincent via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Nov 10 07:46:11 PST 2016
Hi All,
In my adventure to learn a little bit of D coming from C++ I am
now faced with the following problem:
I have read about "cross-module overloading", ยง5.5.2 page 146 of
Andrei Alexandrescu book.
That makes sense to me and this is interesting.
As a concrete example here the scenario: I want to define a
specialized version of the min function.
In D knowing that if there is an ambiguity between modules the
compiler generates an error, the following example does NOT work:
==========================================
// I am the my_min.d file
module my_min;
int min(int a,int b)
{
return (a<b) ? a : b;
}
==========================================
// I am the app.d file
import std.algorithm.comparison;
import my_min;
void main()
{
int a=1,b=2;
auto c=min(a,b); // Compile-time ERROR!
// my_min.min at source/my_min.d:7:5
conflicts with
// std.algorithm.comparison.min!(int,
int).min
auto dc=min(4.5,b); // OK (no ambiguity)
}
==========================================
The D solution is to use the keyword "alias" :
==========================================
// I am the my_min.d file
module my_min;
import std.algorithm.comparison;
int min(int a,int b)
{
return (a<b) ? a : b;
}
alias std.algorithm.comparison.min min; // Here is the magic that
imports
// std min declaration
into my_min module
// and allows "global"
overload resolution
// to take place here, in
my_min module
==========================================
// I am the app.d file
import my_min;
// <- ATTENTION DO NOT RE-import std.algorithm.comparison HERE!
void main()
{
int a=1,b=2;
auto c=min(a,b); // OK! -> use my_min.min
auto dc=min(4.5,b); // OK! -> use std.algorithm.comparison.min
}
==========================================
But now I have the following problem: if I use a parametrized
function min:
==========================================
module my_min;
import std.algorithm.comparison;
T min(T)(T a,T b)
{
return (a<b) ? a : b;
}
alias std.algorithm.comparison.min min; // <- Does NOT compile
anymore
// error: alias my_min.min conflicts with template
my_min.min(T)(T a, T b)
==========================================
-------> What am I missing? What is the right way to do that?
Thank you :)
More information about the Digitalmars-d-learn
mailing list