boost::variant があり、バリアントが特別なタイプの場合にのみファンクターを実行したいので、次の関数を作成しました。
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 を 1 回だけ入力したいと思います。ここではショートタイプですが、実際にはロングタイプもあります。
私はCLang 3.2を使用しています。
完全なテスト ケースは次のとおりです (最初の呼び出しは 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;
}