使用std :: variant而不是编译时错误导致缺少函数重载时引发异常 [英] Throw exception on missing function overload with std::variant instead of compile time error
问题描述
这是对这个问题
请考虑以下代码
#include <variant>
int add_(int a, int b){
return a+b;
}
float add_(float a, float b){
return a+b;
}
float add_(int a, float b){
return a+b;
}
float add_(float a, int b){
return a+b;
}
using Number = std::variant<int, float>;
Number add(Number const& lhs, Number const& rhs ){
return std::visit( []( auto& lhs_, auto& rhs_ )->Number { return {add_( lhs_, rhs_ )}; }, lhs, rhs );
}
int main(){
Number a = 1.f;
Number b = 2.f;
Number c = add(a, b);
}
通过为数字添加越来越多的类型,并可能具有依赖于更多类型的函数比2个参数要清楚的是,我需要定义很多函数,即在std :: variant中找到的所有可能的参数组合。
By adding more and more types to number and potentially having function that depend on more than 2 arguments, it quickly becomes clear, that I need to define a lot of functions, namely all possible parameter combinations that are found in the std::variant.
但是,并非所有组合都是可能的和/或需要的。如果我尝试调用未针对特定参数组合重载的函数,该如何仅定义所需的函数并引发异常?例如,假设我只想保留add_(int,int)或add_(float,float)函数。
However, not all combinations are possible and/or needed. How can I only define the functions I need and throw an exception if I try to call a function that is not overloaded for the particular parameter combination? For example, let's say I only want to keep the add_(int, int) or add_(float, float) function.
推荐答案
我从此网站
template <class ...Fs>
struct overload : Fs... {
overload(Fs const&... fs) : Fs{fs}...
{}
using Fs::operator()...;
};
Number add(const Number& arg0, const Number& arg1){
return std::visit(
overload{
[](int a, int b) -> Number{return add_(a, b);}
,[](float a, float b) -> Number{return add_(a, b);}
,[](auto& a, auto& b) -> Number{throw std::runtime_error("unsupported parameter combination");}
},
arg0, arg1
);
}
这篇关于使用std :: variant而不是编译时错误导致缺少函数重载时引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!