我发现了一个在标准 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
最佳答案
哇。
首先,您“实现”的目标可以通过重载等方式简单得多。其次,它与可选引用完全不同。可选引用是一个值,在运行时可能包含也可能不包含引用。该行为定义明确,但既不可取,也不是可选引用。将对临时对象的引用绑定(bind)为默认参数在某些情况下很好,但距离可选引用还有十亿英里。
关于c++ - 使用通用引用的可选引用技巧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15386888/