调用模板函数时出错
Error in calling template function
我正在开始使用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:usersllovagninisourcereposcloudcachecloudcachecloudcachememoization.cpp(9): error C2146: syntax error: missing ';' before identifier 'anyFunction'
1> c:usersllovagninisourcereposcloudcachecloudcachecloudcachehelloworld.cpp(16): note: see reference to function template instantiation 'std::function<int (void)> converter<int,>(boost::any)' being compiled
1>c:usersllovagninisourcereposcloudcachecloudcachecloudcachememoization.cpp(9): error C2563: mismatch in formal parameter list
1>c:usersllovagninisourcereposcloudcachecloudcachecloudcachememoization.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);
住在科里鲁
#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;
}
}
converter
是一个函数模板,但没有一个模板参数在推导的上下文中,因此您必须显式提供它们:
fun = converter<int,int>(anyFunction);
否则,无法知道该呼叫哪个converter
。
相关文章:
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- PrintWindow函数在notepad.exe中出错
- 使用运算符调用 void 函数时出错<set>
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 在定义的函数中使用常量时出错
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 使用根/C++时出错:没有匹配的构造函数来初始化'TTree'
- Arduino IDE 中使用 strncmp 函数时出错
- 从DLL导出函数,LoadLibrary()需要用TEXT转换的字符串才能编译而不会出错
- 编译包含指向模板函数的指针的初始值设定项列表时,gcc 出错,但 clang 不出错
- 使用一个参数的模板函数时出错(适用于 2)
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 使用类的构造函数时出错
- 在 c++ 的构造函数中分配对象向量时出错
- 为什么在函数参数前面添加 const 会出错?
- 调用析构函数时出错