2017-04-02 69 views
3

來自cppreference,爲什麼std::apply(add_generic, ...)的調用不能編譯?有沒有辦法解決它?爲什麼std :: apply使用泛型函數失敗?

#include <iostream> 
#include <tuple> 

int add(int first, int second) 
{ 
    return first + second;  
} 

template<typename T> 
T add_generic(T first, T second) 
{ 
    return first + second;  
} 

int main() 
{ 
    std::cout << std::apply(add, std::make_tuple(1,2)) << '\n'; 

    // template argument deduction/substitution fails 
    std::cout << std::apply(add_generic, std::make_tuple(2.0f,3.0f)) << '\n'; 
} 

fails錯誤:

[x86-64 gcc 7 (snapshot)] error: no matching function for call to 'apply(, std::tuple)' [x86-64 gcc 7 (snapshot)] note: couldn't deduce template parameter '_Fn'

+0

沒有看到你所得到的錯誤,我想這是可能是因爲無法正確推斷參數類型「T」? –

+0

你是如何編譯代碼的? 'std :: apply'需要'C++ 17',你的編譯器是否支持'C++ 17'? – Rogus

+3

'add_generic'不是一個函數,它是一個模板。你不能從沒有類型的東西中推導出一個類型。 – chris

回答

8

這並不是新的C++ 17。僅從std::apply的簽名中,就不知道您是否想要通過add_generic<int>add_generic<float>add_generic<std::string>或其他任何內容。知道這需要更多的上下文(具體而言:它需要知道std::apply將如何調用它),但該信息在呼叫站點不可用,因此不能用於模板參數推演。

這是可能的解決通過傳遞一個對象,使得調用需要取其add_generic實例化一個對象能夠:

std::cout << std::apply(
    [](auto first, auto second) { return add_generic(first, second); }, 
    std::make_tuple(2.0f,3.0f)) << '\n'; 
相關問題