c++ - overloaded function resolution with std::function: helping compilers disambiguate -


i create std::function overloaded template function. compiling g++ -std=c++14 obtain overload resolution error. have hack massage function template form compiler recognises, know if there more elegant approaches. below code illustrating error , hack,

#include <functional>  template <typename t> t foo(t t) { return t; }  template <typename t> t foo(t t1, t t2){ return t1 + t2; }  int main (){     //error: conversion ‘<unresolved overloaded function type>’      //to non-scalar type ‘std::function<double(double)>’ requested     std::function<double(double)> afunc = &foo<double>;       //my workaround 'show' compiler template      //function instantiate      double (*kmfunc1)(double) = &foo<double>;     std::function<double(double)> afunc = kmfunc1;   } 

i have 2 questions

  • is unreasonable of me expect compiler resolve template use ?
  • what elegant way create std::function above situation?

#define overload_set(...) \   [](auto&&...args)-> \     decltype(__va_args__(decltype(args)(args)...)) \   { \     return __va_args__(decltype(args)(args)...); \   } 

creates single object represents complete (global) overload set of argument. (i use ... macros not understand uses of , in modern c++)

std::function<double(double)> afunc = overload_set(foo<double>); std::function<double(double,double)> bfunc = overload_set(foo<double>); 

both should work, should

std::function<double(double)> afunc = overload_set(foo); std::function<double(double,double)> bfunc = overload_set(foo); 

while @ it. idea here defer overload resolution until point arguments determined.

overload_set(foo) compiles to:

[](auto&&...args) ->decltype(foo(decltype(args)(args)...)) {   return foo(decltype(args)(args)...); } 

which stateless lambda returns whatever invoking foo on arguments do. uses perfect forwarding, usual imperfections.


Comments