我有一个实用程序函数,它遍历一个元组,并且对于每个元素,用该元素调用一个函数,最后用所有元组元素的结果调用另一个函数。
为了更好地说明:
- 有各种类型的元组
tuple<Foo<int>, Bar<double>, Baz<char>>
- 每种类型都有一个隐式接口
Foo
,该接口返回对某个内部成员的引用。Bar
Baz
ClassT::data()
T&
- 你有一个带有签名的函数
void (int, double, char)
该实用程序遍历元组成员,提取对内部成员的引用,并使用所需参数调用函数。
问题:完美转发
我尝试使用所谓的“通用引用”和完美转发来实现该实用程序,从而消除了对多个左值/右值和 const/non-const 重载的需要。
虽然函数的参数是类型
template<typename Tuple>
auto invoke(Tuple&& tuple)
我无法将左值绑定到它。为什么是这样?
我在这里提出了一个类似的问题,这个问题已经解决了;但是,由于这是一个不相关的问题,我相信这需要一个新问题
ideone 示例:https ://ideone.com/lO5JOB
#include <tuple>
#include <iostream>
// sequence
template<size_t...>
struct Sequence
{ };
template<size_t N, size_t... Seq>
struct GenerateSequence : GenerateSequence<N - 1, N - 1, Seq...>
{ };
template<size_t... Seq>
struct GenerateSequence<0, Seq...>
{
using type = Sequence<Seq...>;
};
// invoke tuple
struct TupleForEachInvoker
{
template<typename Func, typename ForEachFunc, typename Tuple, size_t... Seq>
static auto invoke(Func&& func, ForEachFunc&& forEachFunc, Tuple&& tuple, Sequence<Seq...>)
-> decltype(func(forEachFunc(std::get<Seq>(std::forward<Tuple>(tuple)))...))
{
return func(forEachFunc(std::get<Seq>(std::forward<Tuple>(tuple)))...);
}
template<typename Func, typename ForEachFunc, typename... Args>
static auto apply(Func&& func, ForEachFunc&& forEachFunc, std::tuple<Args...>&& args)
-> decltype(invoke(std::forward<Func>(func),
std::forward<ForEachFunc>(forEachFunc),
std::forward<std::tuple<Args...>>(args),
typename GenerateSequence<sizeof...(Args)>::type()))
{
return invoke(std::forward<Func>(func),
std::forward<ForEachFunc>(forEachFunc),
std::forward<std::tuple<Args...>>(args),
typename GenerateSequence<sizeof...(Args)>::type());
}
};
template<typename Func, typename ForEachFunc, typename Tuple>
inline auto invokeWithMemberFromAll(Func&& func, ForEachFunc&& forEachFunc, Tuple&& tuple)
-> decltype(TupleForEachInvoker::apply(std::forward<Func>(func),
std::forward<ForEachFunc>(forEachFunc),
std::forward<Tuple>(tuple)))
{
return TupleForEachInvoker::apply(std::forward<Func>(func),
std::forward<ForEachFunc>(forEachFunc),
std::forward<Tuple>(tuple));
}
// exemplar
template<typename T>
struct Foo
{
T& data() { return _val; }
T _val;
};
struct Extract
{
template<typename T>
T& operator() (Foo<T>& f) { return f.data(); }
};
int main()
{
Foo<int> i { 5 };
Foo<double> d { 6. };
Foo<const char*> s { "hello world" };
auto cb = [](int& i, const double& d, const char* s)
{
std::cout << "i=" << i << ", d=" << d << ", s=" << s << std::endl;
i += 2;
};
// rvalue reference to tuple
invokeWithMemberFromAll(cb, Extract{}, std::tie(i, d, s));
std::cout << i.data() << std::endl;
// lvalue reference to tuple - fails
auto tuple = std::tie(i, d, s);
invokeWithMemberFromAll(cb, Extract{}, tuple);
std::cout << i.data() << std::endl;
}