[英]How to pass a reference to a template typename argument
Is there a way to pass a reference as an argument to a template typename argument?有没有办法将引用作为参数传递给模板类型名参数? I mean so instead of passing an int, for example, to pass a reference to an int.
我的意思是这样,而不是传递 int,例如,传递对 int 的引用。
template <typename T>
struct Foo
{
Foo(T arg) : ptr(arg) {}
T ptr;
};
int main()
{
int* a = new int(6);
Foo<decltype(a)> foo1(a); // ptr is a copy of a pointer
Foo<decltype(&a)> foo1(&a); // ptr seems to be a pointer to a pointer
}
I know I can make the 'ptr' member be a reference to a pointer by making it T& in the class, but I was wondering if this can be done from argument that's passed to the template argument.我知道我可以通过在类中将它设为 T& 来使 'ptr' 成员成为对指针的引用,但我想知道这是否可以通过传递给模板参数的参数来完成。
You're looking for Foo<decltype(a) &> foo1(a)
.您正在寻找
Foo<decltype(a) &> foo1(a)
。
A more obscure alternative (which works in this specific case) is Foo<decltype((a))> foo1(a)
.一个更模糊的替代方案(在这种特定情况下有效)是
Foo<decltype((a))> foo1(a)
。
As an alternative to the previous answer, you can use std::reference_wrapper作为上一个答案的替代方案,您可以使用std::reference_wrapper
std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object.
std::reference_wrapper 是一个类模板,它将引用包装在可复制、可分配的对象中。 It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.
它经常用作将引用存储在通常不能保存引用的标准容器(如 std::vector)中的机制。
#include <functional>
template <typename T>
struct Foo
{
Foo(T arg) : ptr(arg)
{
}
T ptr;
};
int main()
{
int* a = new int(6);
Foo<std::reference_wrapper<int*>> foo1(std::ref(a));
foo1.ptr[0] = 1; // ok
// This also works
int* b = new int(6);
Foo<std::reference_wrapper<decltype(b)>> foo2(std::ref(b));
// and this too
foo1 = foo2;
// Or, if you use c++17, even this
Foo foo3(std::ref(b));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.