auto generate "reference" to overloaded functions

59 views
Skip to first unread message

wei zhang

unread,
Jun 20, 2017, 11:45:06 PM6/20/17
to ISO C++ Standard - Future Proposals

Normally, we cannot refer to an overloaded function by only name, because the function pointers are not the only one.  We must qualified the function with the whole parameter list so as to get the actual one function pointer.
But we can create a functional class and wrap calling the overloaded functions by overload operator ()
Here's the sample:


float Minus(float a, float b);
int   Minus(int a, int b);
double  Minus(double a, double b);

template<Func, P1, P2 > 
decltype(declval<Func>()(P1(), P2())) CheckAndDo( Func func,  P1 p1, P2 p2)
{
    if( p1 < 0 || p2 < 0 )
return decltype(Func(P1,P@)) 0;
    return func(p1, p2);
}

// compile failed, because Minus does not belong to an actual type. Compiler cannot know which Function it is
CheckAndDo(&Minus, 10, 5);

//but still we can construct a type which can handle that 
class Overload_Minus{
public:
    float operator()(float a, float b)
{
   return Minus(a,b);
}
int operator()(int a, int b)
{
return Minus(a,b);
}
double operator()(double a, double b)
{
return Minus(a,b);
}
};

// So that now we can calls
Overload_Minus minus;
int a = CheckAndDo(minus, 1, 2);


I think, this Overload_ class can be created anonymously by compiler automatically.  Like

auto minus = overloaded Minus;  // here with a new keyword overloaded to force tell compiler to create an annoymous Functional class
auto minus = Minus;   // or maybe, we can imply the creation of the annoymouse class if there's no broken for c++ language

Further, we might do some filter when creating anonymous class
Sample:
Assumes we have 6 overloaded functions, by 2 groups.  We can filter them with First Parameter Type
void print_to_strings(std::string &, int);
void print_to_strings(std::string &, double);
void print_to_strings(std::string &, float);

void print_to_strings(std::wstring &, int);
void print_to_strings(std::wstring &, double);
void print_to_strings(std::wstring &, float);

auto print_to_wstring = overloaded<T>(std::wstring&, T ) print_to_strings;
// 
print_to_wstring will now only refer to the last 3 functions.  
// Any calls to print_to_wstring by a std::string will meet a compile error, because it didn't provide operator(std::string, *)





Message has been deleted

Jakob Riedle

unread,
Jun 21, 2017, 5:32:46 AM6/21/17
to ISO C++ Standard - Future Proposals
Hi Wei Zhang,

Great Idea. This has already been talked on e.g. by P0119.

Cheers,
Jakob
Reply all
Reply to author
Forward
0 new messages