【发布时间】:2018-01-31 00:04:22
【问题描述】:
我有一个类似于std::apply 的很好的实现,它将元组扩展为函数的参数。它工作得很好,除了 std::get 总是返回一个左值并且它无法匹配正确的重载。
POC 代码可以在这里找到:https://wandbox.org/permlink/OUYMQY2afL8vRMUu
这个想法是将std::forward 添加到apply_sequence 以便打印ONE TWO THREE
void printNumber(const int& x, const int& y)
{
std::cout << "ONE" << std::endl;
}
void printNumber(const int& x, int&& y)
{
std::cout << "TWO" << std::endl;
}
void printNumber(int&& x, const int& y)
{
std::cout << "THREE" << std::endl;
}
template<typename... TTuple, std::size_t... Indices>
auto apply_sequence(const std::tuple<TTuple...>& tuple, std::index_sequence<Indices...>)
{
// missing: forward value to proper type (currently is always lvalue)
return printNumber(std::get<Indices>(tuple)...);
}
template<typename... TTuple>
auto apply_tuple(const std::tuple<TTuple...>& tuple)
{
return apply_sequence(tuple, std::index_sequence_for<TTuple...>());
}
int main(int argc, char* argv[])
{
std::tuple<int, int> one { 1, 2 };
apply_tuple(one); // ONE
std::tuple<int, int&&> two { 1, 2 };
apply_tuple(two); // TWO
std::tuple<int&&, int> three { 1, 2 };
apply_tuple(three); // THREE
return 0;
}
编辑:如果有人想要解决问题https://wandbox.org/permlink/XkUjfypAMepJRPgZ
【问题讨论】:
-
我建议您将post 代码在此处作为minimal reproducible example。
-
在您的代码示例中,您的重载的唯一区别是
int与int&&are indistinguishable -
@SirGuy 你是对的,我更新了例子
标签: c++ tuples forward perfect-forwarding