我正在尝试创建一个访问者函数,它将我的 boost::variant
的值加在一起。 .我在类型不同的情况下使用模板,例如 int + float
typedef boost::variant<int, float> Values;
struct Add : public boost::static_visitor<Values> {
template <typename T, typename U>
auto operator() (T a, U b) const -> decltype(a + b) {
return a + b;
}
}
这编译并正常工作
std::cout << boost::apply_visitor(Add{}, (Values)2, (Values)5) << std::endl;
std::cout << boost::apply_visitor(Add{}, (Values)2, (Values)5.123) << std::endl;
7
7.123
但是我也想添加一个
std::string
进Values
变体,所以我也可以将字符串相加。我知道这是不可能的 string + int
例如,但我会确保 Values
在尝试通过访问者运行它们之前是一个字符串。typedef boost::variant<int, float, std::string> Values;
std::cout << boost::apply_visitor(Add{}, (Values)"hello", (Values)"world") << std::endl;
但是程序没有编译,给了我错误:
Failed to specialize function template 'unknown-type Add::operator ()(T,U) const'
我知道
std::string
是一个对象而不是一个类型,因此这种错误是有道理的,所以我试图通过重载 operator
来制造一个特例。在 Add
当输入都是字符串时的结构:auto operator() (std::string a, std::string b) const {
return a + b;
}
但是我得到了错误
std::basic_string,std::allocator> Add::operator ()(std::string,std::string) const': cannot convert argument 1 from 'T' to 'std::string'
看起来它仍在尝试通过模板化访问者运行字符串参数。我哪里错了?有没有更好的方法来实现我想要做的事情?对不起,如果答案很明显,我对 C++、boost 和模板还是很陌生。
最佳答案
apply_visitor
应该处理所有组合(即使你无效)。
你可能会这样做:
using Values = boost::variant<int, float, std::string>;
// Helper for overload priority
struct low_priority {};
struct high_priority : low_priority{};
struct Add : public boost::static_visitor<Values> {
template <typename T, typename U>
auto operator() (high_priority, T a, U b) const -> decltype(Values(a + b)) {
return a + b;
}
template <typename T, typename U>
Values operator() (low_priority, T, U) const {
// string + int, float + string, ...
throw std::runtime_error("Incompatible arguments");
}
template <typename T, typename U>
Values operator() (T a, U b) const {
return (*this)(high_priority{}, a, b);
}
};
关于c++ - boost::static_visitor 未能专门化具有多种不同可能类型的函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61501500/