c++ - 使用通用引用的可选引用技巧?

标签 c++ templates c++11 pass-by-reference universal-reference

我发现了一个在标准 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/

相关文章:

c++ - 如果模板类型也可以是字符串,如何将其转换为字符串?

c++ - 为什么我要在不存储 ptr 的情况下调用 new?

c++ - 从基类调用函数

c++ - gdb vector 尝试获取不在内存中的地址

javascript - 如何忽略 Mustache 模板中的 Handlebars 表达式?

templates - 使用表达式或类型名 (DLang) 调用的 D 模板

C++如何用模板特化或其他方式实现?

c++ - 类型别名中的详细类型说明符

c++ - 用于在 QLabel 上对齐非恒定宽度文本的通用代码

c++ - 解压 C++ 指针/引用语法