我开始使用boost::any
并且我试图定义一个给出std::function
参数(最初是std::function
个对象)的函数转换它回到#include <iostream>
#include <functional>
#include <boost/any.hpp>
using namespace std;
typedef function<int(int)> intT;
template <typename ReturnType, typename... Args>
std::function<ReturnType(Args...)> converter( boost::any anyFunction) {
return boost::any_cast<function<ReturnType(Args...)>> (anyFunction);
}
int main()
{
intT f = [](int i) {return i; };
boost::any anyFunction = f;
try
{
intT fun = boost::any_cast<intT>(anyFunction);//OK!
fun = converter(anyFunction);//ERROR!
}
catch (const boost::bad_any_cast &)
{
cout << "Bad cast" << endl;
}
}
。
1>c:\users\llovagnini\source\repos\cloudcache\cloudcache\cloudcache\memoization.cpp(9): error C2146: syntax error: missing ';' before identifier 'anyFunction'
1> c:\users\llovagnini\source\repos\cloudcache\cloudcache\cloudcache\helloworld.cpp(16): note: see reference to function template instantiation 'std::function<int (void)> converter<int,>(boost::any)' being compiled
1>c:\users\llovagnini\source\repos\cloudcache\cloudcache\cloudcache\memoization.cpp(9): error C2563: mismatch in formal parameter list
1>c:\users\llovagnini\source\repos\cloudcache\cloudcache\cloudcache\memoization.cpp(9): error C2298: missing call to bound pointer to member function
这是返回的错误:
converter
你能帮我理解我错在哪里吗?
更新
我解决了parantheses问题,但知道编译器抱怨,因为我在没有指定任何类型的情况下调用converter<int,int>
...有什么方法可以保持它的通用性?对于我的应用程序而言,指定|
答案 0 :(得分:2)
你...忘了添加parens:
return boost::any_cast<std::function<ReturnType(Args...)> >(anyFunction);
接下来,您无法推断出模板参数,因此您必须指定它们:
fun = converter<int, int>(anyFunction);
<强> Live On Coliru 强>
#include <iostream>
#include <functional>
#include <boost/any.hpp>
typedef std::function<int(int)> intT;
template <typename ReturnType, typename... Args>
std::function<ReturnType(Args...)> converter(boost::any anyFunction) {
return boost::any_cast<std::function<ReturnType(Args...)> >(anyFunction);
}
int main()
{
intT f = [](int i) {return i; };
boost::any anyFunction = f;
try
{
intT fun = boost::any_cast<intT>(anyFunction); // OK!
fun = converter<int, int>(anyFunction); // OK!
}
catch (const boost::bad_any_cast &)
{
std::cout << "Bad cast" << std::endl;
}
}
答案 1 :(得分:1)
converter
是一个函数模板,但没有一个模板参数位于推导的上下文中,因此您必须明确提供它们:
fun = converter<int,int>(anyFunction);
否则,无法知道要调用哪个 converter
。