gpt4 book ai didi

c++ - 调用模板函数出错

转载 作者:行者123 更新时间:2023-11-28 00:04:02 25 4
gpt4 key购买 nike

我开始使用 boost::any我正在尝试定义一个给定 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没有指定任何类型......有什么方法可以保持它的通用性?不指定 converter<int,int> 对我的申请非常重要

最佳答案

你...忘记添加括号:

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;
}
}

关于c++ - 调用模板函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36769268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com