2013-04-09 75 views
2
#include <array> 
#include <functional> 

template<typename T, typename ... Args> 
auto make_array(T&& t, Args&& ... args) -> std::array<T, sizeof...(Args)+1> { 
    return {std::forward<T>(t), std::forward<Args>(args)...}; 
} 

int main() { 
    auto f = [](int i)->int { return i; }; 
    auto f2 = [](int i)->int { return i*2; }; 

    auto arr2 = make_array<std::function<int(int)>>(f, f2); 

    return 0; 
} 

有沒有辦法在調用站點make_array<std::function<int(int)>>處指定模板類型?std :: array和lambda

回答

3

可以推導出參數類型。隨着this clever solution通過ecatmur就可以自動生成合適的std::function<>對象:

template<typename T, typename ... Args> 
auto make_array(T&& t, Args&& ... args) -> 
    std::array<make_function_type<T>, sizeof...(Args)+1> 
//    ^^^^^^^^^^^^^^^^^^^^^ 
{ 
    return {std::forward<T>(t), std::forward<Args>(args)...}; 
} 

#include <iostream> 

int main() 
{ 
    auto f = [](int i)->int { return i; }; 
    auto f2 = [](int i)->int { return i*2; }; 

    auto arr2 = make_array(f, f2); 
    std::cout << arr2[1](21); // Prints 42 

    return 0; 
} 

這裏是一個live example