Yun*_*ang 1 c++ logging functional-programming c++11
我尝试将std :: log作为函数参数传递,但似乎有std :: log的重载实现,并且编译器无法解析它.代码:
#include <cmath>
#include <iostream>
#include <vector>
#include <string>
#include <functional>
template <typename FOper>
double Eval(FOper fOper, double X)
{
return fOper(X);
}
int main(int argc, char* argv[])
{
std::function<double(double)> fPlus1 = std::bind(std::plus<double>(), 1.0, std::placeholders::_1);
std::cout<<Eval(fPlus1, 10.0)<<std::endl;
// how to write this fLog ?
//std::function<double(double)> fLog = std::log;
//std::function<double(double)> fLog = std::log<double>;
std::cout<<Eval(fLog, 10.0)<<std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释fLog定义的任一行,则编译器会提示错误消息:
error: conversion from '<unresolved overloaded function type>' to non-scalar type 'std::function<double(doubl
e)>' requested
Run Code Online (Sandbox Code Playgroud)
最简单的方法是简单地投射它:
typedef double (*log_d)(double);
std::function<double(double)> fLog = static_cast<log_d>(std::log);
Run Code Online (Sandbox Code Playgroud)
使用强制转换,您可以向编译器提供使用重载函数的上下文,因此将从中获取正确的函数指针.
| 归档时间: |
|
| 查看次数: |
803 次 |
| 最近记录: |