템플릿 typename 인수에 인수로 참조를 전달하는 방법이 있습니까? 예를 들어 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 & 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));
}