我開始使用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
能否請你幫我瞭解我在哪裏錯了?
UPDATE 我解決了這個括號問題,但知道編譯器會抱怨,因爲我叫converter
不指定任何類型的...還有就是要保持通用的什麼辦法?
return boost::any_cast<std::function<ReturnType(Args...)> >(anyFunction);
接下來,你不能推導出模板ARGS,所以你必須指定它們:我的應用程序不指定converter<int,int>
如果你不想指定轉換器,那麼你基本上有intT轉換器(boost :: any anyfunction)。但後來我不禁想知道你真的想做什麼,而不是如何... –
OnMyLittleDuck
爲所有人服務^ – sehe
我不知道我必須爲多種類型模板指定至少一種類型。 – justHelloWorld