调用模板函数时出错

Error in calling template function

本文关键字:出错 函数 调用      更新时间:2023-10-16

我正在开始使用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