我有一個boost ::變種,我想只執行,如果變體是一種特殊類型的函子,所以我做了這個功能:如何使用lambda在std :: function參數中推導出模板類型?
template<typename T, typename Variant>
void if_init(Variant& opt_variant, std::function<void(T)> functor){
if(auto* ptr = boost::get<T>(&opt_variant)){
functor(*ptr);
}
}
這工作不錯,但我想T型被推斷,這樣我可以寫:
if_init(b, [](double var){ std::cout << "I'm double and set" << std::endl; });
但類型不會推導出:
type_inference.cpp:19:5: error: no matching function for call to 'if_init'
if_init(b, [](double var){ std::cout << "I'm double and set" << std::endl; });
^~~~~~~
type_inference.cpp:10:6: note: candidate template ignored: failed template argument deduction
void if_init(Variant& opt_variant, std::function<void(T)> functor){
如果我寫:
if_init<double>(b, [](double var){ std::cout << "I'm double and set" << std::endl; });
它運作良好。
有沒有辦法讓T型被推斷出來?我只想輸入一次T.這裏的類型很短,但在實際情況下,類型很長。
我正在使用CLang 3.2。
以下是完整的測試用例(第一次調用編譯沒有第二個):
#include <iostream>
#include <functional>
#include <boost/variant.hpp>
typedef boost::variant<int, double> Test;
template<typename T, typename Variant>
void if_init(Variant& opt_variant, std::function<void(T)> functor){
if(auto* ptr = boost::get<T>(&opt_variant)){
functor(*ptr);
}
}
int main(){
Test b = 1.44;
if_init<double>(b, [](double var){ std::cout << "I'm double and set" << std::endl; });
if_init(b, [](int var){ std::cout << "I'm int and set" << std::endl; });
return 0;
}
好的,我不知道std :: function沒有強制執行:(但是,如果我只使用typename Functor,它不會改變T不會被推斷的事實,對吧? –
2013-02-09 03:34:22
@BaptisteWicht是。在這種情況下,你可以要求'Functor'是單形的並且提取它的單個參數類型。這不是我通常做的事情(我真的試圖避免檢查函子,因爲這對於多態函數不起作用),我無法想象一個特質能夠完成這項工作。 – 2013-02-09 03:51:11