[英]How to pass a reference to a template typename argument
有沒有辦法將引用作為參數傳遞給模板類型名參數? 我的意思是這樣,而不是傳遞 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
}
我知道我可以通過在類中將它設為 T& 來使 'ptr' 成員成為對指針的引用,但我想知道這是否可以通過傳遞給模板參數的參數來完成。
您正在尋找Foo<decltype(a) &> foo1(a)
。
一個更模糊的替代方案(在這種特定情況下有效)是Foo<decltype((a))> foo1(a)
。
作為上一個答案的替代方案,您可以使用std::reference_wrapper
std::reference_wrapper 是一個類模板,它將引用包裝在可復制、可分配的對象中。 它經常用作將引用存儲在通常不能保存引用的標准容器(如 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.