I would like to create a std::function
from an overloaded template function. Compiling with g++ -std=c++14 I obtain an overload resolution error. I have a hack to massage the function template into a form which the compiler recognises, but I would like to know if there are more elegant approaches. Below is code illustrating the error and my 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 from ‘<unresolved overloaded function type>’
//to non-scalar type ‘std::function<double(double)>’ requested
std::function<double(double)> afunc = &foo<double>;
//my workaround to 'show' compiler which template
//function to instantiate
double (*kmfunc1)(double) = &foo<double>;
std::function<double(double)> afunc = kmfunc1;
}
I have two questions
- Is it unreasonable of me to expect the compiler to resolve which template to use ?
- What is the most elegant way to create the std::function is the above situation?