2016-12-01 85 views
2

我想使使用的std ::函數的返回值類型通用的,但它不工作,代碼: 調試代碼,可以發現:http://cpp.sh/5bk5如何從std :: function中推斷返回值類型?

class Test 
{ 
public: 
    template <typename R, typename F = std::function<R()>> 
    R f(F&& op) { 
    op(); 
    } 

    void t() { 
    int a = 10; 
    f([this, a]() { return "chars"; }); 
    } 
}; 

int main() 
{ 
    t::Test test; 
    test.t(); 
    return 0; 
} 
+0

也許用'result_of'讓你可以只編譯C++ 11在返回類型? –

+0

您是否嘗試過使用void *?這是Cish的方式有泛型類型。 – mgarey

回答

2

你可以避開模板/ std::function方式並使用auto作爲返回類型。

如果你可以編譯C++ 14很容易

// Example program 
#include <iostream> 

class Test 
{ 
    public: 
     Test(){ } 

     template <typename F> 
     auto f (F && op) 
     { return op(); } 

     void t() 
     { std::cout << f([this]() { return "chars"; }) << std::endl; } 
}; 


int main() 
{ 
    Test test; 

    test.t(); 

    return 0; 
} 

如果你必須使用decltype()Test::f()

template <typename F> 
    auto f (F && op) -> decltype(op()) 
    { return op(); } 
相關問題