【发布时间】:2015-07-15 11:27:31
【问题描述】:
我想从一个重载的模板函数创建一个std::function。使用 g++ -std=c++14 编译我得到一个重载解析错误。我有一个技巧可以将函数模板按摩成编译器可以识别的形式,但我想知道是否有更优雅的方法。下面是说明错误和我的 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;
}
我有两个问题
- 我期望编译器解析使用哪个模板是不合理的吗?
- 在上述情况下,创建 std::function 最优雅的方法是什么?
【问题讨论】:
-
也可以使用
[](double d){return f(d);}代替演员表,或者通过std::function<double(double)> afunc = static_cast<double(*)(double)>(foo);稍微更优雅的演员表(尽管那个演员表太明确了恕我直言)甚至template<class Sig> std::function<Sig> make_function(Sig* f) { return {f}; } auto afunc = make_function<double(double)>(foo); -
顺便说一句,这就是我认为
std::function应该有一个Sig* pf构造函数的原因之一,也是为什么我的std::function-likes 有这样一个重载的原因。
标签: c++ templates c++11 overloading