考虑下面的代码:完美转发和std ::元组
#include <iostream>
#include <tuple>
#include <utility>
// A.
template <typename... Args>
void f (const char* msg, Args&&... args)
{
std::cout << "A. " << msg << "\n";
}
// B.
template <typename... Args>
void f (const char* msg, std::tuple<Args...>&& t)
{
std::cout << "B. " << msg << "\n";
}
struct boo
{
const std::tuple<int, int, long> g() const
{
return std::make_tuple(2, 4, 12345);
}
};
int main()
{
f("First", 2, 5, 12345);
f("Second", std::make_tuple(2, 5, 12345));
boo the_boo;
f("Third", the_boo.g());
f("Fourth", std::forward<decltype(std::declval<boo>().g())>(the_boo.g()));
return 0;
}
的输出将是:
A. First
B. Second
A. Third
A. Fourth
从它的明显,它不这样做,我想什么输出它要做的,就是我想第三个和第四个要经过B.版本的函数。 The std ::转发从第四电话是多余的,因为完美的转发不会发生在那里。为了拥有完美的转发我知道:
- 我必须在一个类型推导上下文
- 参数的类型的右值引用必须是功能
我明白了一个模板类型这是行不通的。但我不充分掌握:
为什么上下文是通过使用的std ::元组在这样一种方式,它不能根据需要工作改变了吗?为什么模板参数不能用于另一个模板类型的 ?
我该如何(优雅地)修复它?
有更大的问题'B'是你的非const右值引用不能绑定到一个const右值。 – 2015-02-11 09:50:38
我明白了。编译器告诉我同样的事情(修改一些代码)。我只是看不到如何解决它。 – celavek 2015-02-11 09:53:38
没有'g'返回一个const元组? (为什么它会返回一个呢?) – 2015-02-11 09:58:49