gpt4 book ai didi

c++ - 如何返回由 boost::varaint 返回类型中包含的类型的子集构成的 boost::variant

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:07:37 24 4
gpt4 key购买 nike

我有 4 个函数:

boost::variant<type1,type2,type3>processFile(const char* file){
if(----expression that if true means I have to process as type 1----)
return processType1(file); //this just returns type1
else if(----expression that if true means I have to process as either type 1 or type 2----)
return processType23(file); //this returns boost::variant<type2,type3>. This also calls 2 more processing functions depending on type.
}

processType23 接受一个脚本文件,该文件将确定返回哪种类型。我想在这个文件中保留类型的确定。但是我不能返回 boost::variant。我收到以下错误:

error: could not convert 'engine::fileManager::processLua(const char*)()' from 'boost::variant<engine::material, engine::shader>' to 'boost::variant<engine::material, engine::shader, unsigned int>'

返回数据的(正确)方式是什么?

最佳答案

你应该使用访问者:

Live On Coliru

template <typename R, typename A> convert_variant(A const& arg) {
return boost::apply_visitor([](auto const& v) -> R { return R{v}; }, arg);
}

更新

针对@llonesmiz 的观察,您可能希望编译转换代码,即使某些转换可能是非法的。在那种情况下,您将不得不使用一些类型特征来区分这些情况并采取相应的行动:

C++03 演示

Live On Coliru

#include <boost/variant.hpp>
#include <boost/type_traits.hpp>
#include <iostream>

template <typename R>
struct convert_variant_visitor : boost::static_visitor<R> {
struct bad_conversion : std::runtime_error {
bad_conversion(std::string msg) : std::runtime_error(msg) {}
};

template <typename T>
typename boost::enable_if_c<boost::is_convertible<T, R>::value, R>::type
operator()(T const& v) const
{
return R(v); // or just v
}

template <typename T>
typename boost::enable_if_c<not boost::is_convertible<T, R>::value, R>::type
operator()(T const& v) const
{
throw bad_conversion(std::string("Cannot convert ") + typeid(v).name() + " to " + typeid(R).name());
//throw bad_conversion("Not convertible to variant");
}
};

template <typename R, typename A> R convert_variant(A const& arg) {
return boost::apply_visitor(convert_variant_visitor<R>(), arg);
}

int main() {
typedef boost::variant<std::string, int, double> V1;
typedef boost::variant<int, double> V2;
V1 input = 42;
V2 output = convert_variant<V2>(input);

std::cout << "input: " << input << " (which: " << input.which() << ")\n";
std::cout << "output: " << output << " (which: " << output.which() << ")\n";
}

打印

input:  42 (which: 1)
output: 42 (which: 0)

C++17 演示

现代 C++ 功能正在使这样的通用代码变得更加简单:

Live On Coliru

template <typename R, typename A> R convert_variant(A const& arg) {
return boost::apply_visitor([](auto const& v) -> R {
if constexpr (std::is_convertible_v<decltype(v), R>)
return v;
else
throw std::runtime_error("bad conversion");
} , arg);
}

关于c++ - 如何返回由 boost::varaint 返回类型中包含的类型的子集构成的 boost::variant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47195247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com