This is the follow-up question for A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++. As G. Sliepen's answer mentioned, leaving only recursively transforming operation for recursive_transform()
may be a better idea. As the result, the implementation of recursive_transform
function is kept in the following form. Moreover, the forward declarations have been removed.
template<class T, class _Fn> requires is_iterable<T>
static inline T recursive_transform(const T input, _Fn func)
{
T returnObject = input;
std::transform(input.begin(), input.end(), returnObject.begin(), func);
return returnObject;
}
template<class T, class _Fn> requires is_iterable<T> && is_element_iterable<T>
static inline T recursive_transform(const T input, _Fn func)
{
T returnObject = input;
std::transform(input.begin(), input.end(), returnObject.begin(),
[func](const auto& element)
{
return recursive_transform(element, func);
}
);
return returnObject;
}
However, I still want to handle the compound structure with ranges and std::variant
, such as std::vector<std::variant<double>>
. A new function get_from_variant
comes up in my mind in order to focus on the operations with these things.
template<typename T_variant, typename T>
static inline auto get_from_variant(T_variant input_variant)
{
T return_val;
std::visit([&](auto&& arg)
{
return_val = static_cast<T>(arg);
return arg;
},
input_variant);
return return_val;
}
The tests of this get_from_variant
function:
int main()
{
// get_from_variant function test
std::variant<double> testNumber = 1;
std::cout << get_from_variant<decltype(testNumber), double>(testNumber);
// The usage of recursive_transform function and get_from_variant function
std::variant<double> variant_number = 3.14;
std::vector<decltype(variant_number)> testVector1;
testVector1.push_back(variant_number);
testVector1.push_back(variant_number);
testVector1.push_back(variant_number);
std::cout << get_from_variant<std::variant<double>, double>(recursive_transform(testVector1, [](auto x){ return get_from_variant<std::variant<double>, double>(x) + 1; }).at(0)) << std::endl;
return 0;
}
All suggestions are welcome.
Which question it is a follow-up to?
What changes has been made in the code since last question?
In order to handle the compound structure with ranges and
std::variant
, such asstd::vector<std::variant<double>>
in a better way, a new functionget_from_variant
has been created.Why a new review is being asked for?
In my opinion, I am not sure whether the design of the function
get_from_variant
is good? Is the idea or the usage good or not? Any comment is welcome.
get_from_variant()
might not be the best name, as there's alreadystd::get()
for variants. Some languages already have avariant_cast
, but that casts between two different variants. Maybeget_as()
is better? \$\endgroup\$