[英]C++ variadic template arguments: object is not forwarded as a reference
Let's say I have the following code:假设我有以下代码:
#include <iostream>
struct NotCopyable
{
std::string value;
NotCopyable(const std::string& str) :
value(str)
{
}
// This struct is not allowed to be copied.
NotCopyable(const NotCopyable&) = delete;
NotCopyable& operator =(const NotCopyable&) = delete;
};
struct Printable
{
NotCopyable& nc;
// This struct is constructed with a reference to a NotCopyable.
Printable(NotCopyable& inNc) :
nc(inNc)
{
}
// So that std::cout can print us:
operator const char*() const
{
return nc.value.c_str();
}
};
// This function constructs an object of type T,
// given some arguments, and prints the object.
template<typename T, typename... ARGS>
void ConstructAndPrint(ARGS... args)
{
T object(std::forward<ARGS>(args)...);
std::cout << "Object says: " << object << std::endl;
}
int main(int, char**)
{
// Create a NotCopyable.
NotCopyable nc("123");
// Try and construct a Printable to print it.
ConstructAndPrint<Printable>(nc); // "Call to deleted constructor of NotCopyable"
// OK then, let's make absolutely sure that we're forwarding a reference.
NotCopyable& ncRef = nc;
// Try again.
ConstructAndPrint<Printable>(ncRef); // "Call to deleted constructor of NotCopyable"
}
It seems that the NotCopyable
isn't being forwarded properly as a reference, even when I explicitly supply a reference variable as the argument.似乎NotCopyable
没有作为参考正确转发,即使我明确提供参考变量作为参数也是如此。 Why is this?为什么是这样? Is there any way I can ensure that a reference is forwarded, and not a copy-constructed object?有什么方法可以确保转发引用,而不是复制构造的 object?
template<typename T, typename... ARGS>
void ConstructAndPrint(ARGS... args);
take argument by value, so does copy.按值取参数,复制也是如此。
You want forwarding reference instead:您想要转发参考:
// This function constructs an object of type T,
// given some arguments, and prints the object.
template<typename T, typename... ARGS>
void ConstructAndPrint(ARGS&&... args)
{
T object(std::forward<ARGS>(args)...);
std::cout << "Object says: " << object << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.