2016-04-21 72 views
0

我開始使用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>

+1

如果你不想指定轉換器,那麼你基本上有intT轉換器(boost :: any anyfunction)。但後來我不禁想知道你真的想做什麼,而不是如何... – OnMyLittleDuck

+0

爲所有人服務^ – sehe

+0

我不知道我必須爲多種類型模板指定至少一種類型。 – justHelloWorld

回答

2

你......忘了加括號,這將是非常重要的:

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

同時更新:D – justHelloWorld

1

converter是一個函數模板,但沒有一個模板參數是一個推導的情境,所以你必須明確地爲他們提供:

fun = converter<int,int>(anyFunction); 

否則就沒有辦法知道converter調用哪個。