c++ - boost::static_visitor 未能专门化具有多种不同可能类型的函数模板

标签 c++ templates boost operator-overloading sfinae

我正在尝试创建一个访问者函数,它将我的 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::stringValues变体,所以我也可以将字符串相加。我知道这是不可能的 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/

相关文章:

c++ - 将 Protocol Buffer 定义拆分为多个 .proto 文件

html - 如何在 Golang 中设置 HTML <select> 元素的默认值?

c++ - 模棱两可的错误 : C++11 use variadic template multiple inheritance

c++ - std::optional 和 boost::optional 是否遵守托管对象的对齐限制?

c++ - boost::bind 隐式转换为 boost::function 或函数指针

c++ - 如何在 yaml-cpp 中发出带有额外换行符的映射序列

c++ - 如何阻止 CMake 将特定于平台的标志传递给编译器?

c++ - 在 C++ 中编译多个 .hpp 和 .cpp 文件时出错

c++ - 什么时候将全局变量的地址作为模板参数传递有用?

c++ - Boost-Beast 异步网络套接字服务器-客户端异步读写不在控制台上写入输出