问题描述
给出代码:
#include <iostream>
#include <functional>
#include <type_traits>
using ftype = int ( int ) ;
using function_type = std::function<ftype> ;
struct STest
{
STest(bool b) { }
STest(function_type f) { }
};
int AFunction ( int parm )
{
return (parm + 1);
}
int main()
{
STest ss(&AFunction);
return 0;
}
main()函数中'ss'的构造导致使用带有布尔值的构造函数,而我希望使用带有function_type的构造函数。显然,我可以通过以下方法在呼叫者站点解决此问题:
STest ss(&AFunction);
到
STest ss(static_cast<function_type>(&AFunction));
,将使用采用function_type的构造函数。但是有什么方法可以更改STest结构中被调用者站点上的代码,从而即使使用STest ss(&AFunction);
作为代码,也可以使用采用函数类型的构造函数,而无需更改每个函数的类型。构造函数。
解决方法
您似乎唯一的要求是不更改现有的构造函数。
但是您没有说不添加另一个过载:
STest(ftype f) : STest{function_type{f}} {}
正确的重载被委托给了。
,您可以将函数类型从std::function
更改为函数指针:
using function_type = int(*)(int);
现在STest(function_type f)
可以被调用而无需强制转换,因此它总是比STest(bool b)
更受青睐。