표준 C++ 11에서 선택적 참조를 사용하는 트릭을 발견했습니다. 이 기술이 안정적이며 동작이 C++ 표준에 따라 잘 정의되어 있다고 생각합니까?범용 참조를 사용하는 선택적 참조의 트릭이 있습니까?
// Optional reference using C++11
// V. Reverdy - 2013
#include <iostream>
#include <type_traits>
template <class T = int, class = typename std::enable_if<std::is_same<typename std::decay<T>::type, int>::value>::type>
void f(T&& n = T())
{
std::cout<<"--------"<<std::endl;
std::cout<<"is const = "<<std::is_const<T>::value<<std::endl;
std::cout<<"is reference = "<<std::is_reference<T>::value<<std::endl;
std::cout<<"is lvalue reference = "<<std::is_lvalue_reference<T>::value<<std::endl;
std::cout<<"is rvalue reference = "<<std::is_rvalue_reference<T>::value<<std::endl;
std::cout<<"--------"<<std::endl;
n *= 2;
}
int main(int argc, char* argv[])
{
int n = 42;
std::cout<<"n = "<<n<<std::endl;
f();
std::cout<<"n = "<<n<<std::endl;
f(n);
std::cout<<"n = "<<n<<std::endl;
return 0;
}
결과는 다음과 같습니다
n = 42
--------
is const = 0
is reference = 0
is lvalue reference = 0
is rvalue reference = 0
--------
n = 42
--------
is const = 0
is reference = 1
is lvalue reference = 1
is rvalue reference = 0
--------
n = 84
이 liveworkspace에서 사용할 수있는 모든 컴파일러에서 작동하는 것 같다 : LWS
실제 사용 사례가 있습니까? – Mat
재미있는 부분은'int','int &','int &&'와'int const &'사이에'T' 타입 타입이 있습니다. 여러분이 아무것도 전달하지 않으면'int' 선택이 일어납니다. 매개 변수없이'int'를 얻는 이유는'T'가 더 이상 추론되지 않고'T &&'가 더 이상 유형 공제 문맥에서 사용되지 않는다는 것을 의미하는 템플릿 인자의 기본값이 사용되기 때문입니다. 이 함수에서'std :: is_reference :: value'을 시도해보십시오. 기술의 단점은'T'가 때로는 공제 문맥에 있고 때로는 그렇지 않다는 것입니다. –
Yakk