add_lvalue_reference有什么作用?

shu*_*e87 8 c++ c++11

我有这个类为montecarlo模拟器创建一个路径,它从一个可用的int数组创建整数路径.因此,例如,我们可以有从含有数组{0,1,2,3,4}拉伸长度为3的路径,这将例如生成3,1,2和1,4,0​​.

//This path generator just generates a list of ints for each path
template< typename randgen >
class MCPathGen {
    public:
        typedef vector< int > mcpath_t;
        typedef randgen randgen_t;
        typedef typename add_lvalue_reference<randgen>::type randgen_ref_t;

        MCPathGend(randgen_ref_t r) : m_rgen(r) {}

        //generate a single path by shuffling a copy of blank_d
        mcpath_t operator()() {
            Chooser< randgen_t > choose(m_rgen);
            mcpath_t path_temp(blank_d.begin(), blank_d.end());
            random_shuffle(path_temp.begin(), path_temp.end(), choose);

            return path_temp;
        };

    private:
        randgen_ref_t m_rgen;

};
Run Code Online (Sandbox Code Playgroud)

现在我不太确定我的同事使用了什么 typedef typename add_lvalue_reference<randgen>::type randgen_ref_t;

add_lvalue_reference有什么作用?这对于使代码有效是必要的吗?

我以前没见过,所以任何见解都值得赞赏!

Ben*_*igt 7

复制伪随机数生成器意味着您将从每个生成相同的"随机"数字流,这是不可取的,因此您需要在那里引用.

但是,你可以这么说randgen&.

根据[dcl.ref]草案3225,randgen&无论传入什么(type,lvalue-reference-type或rvalue-reference-type),都会创建一个左值引用,所以我只是使用它.

从控制此行为的标准引用:

如果typedef(7.1.3),类型模板参数(14.3.1)或decltype-speci er er(7.1.6.2)表示作为类型TR引用的类型T,则尝试创建类型"左值引用" to cv TR "创建类型"左值引用T",而尝试创建类型"rvalue引用cv TR "创建类型TR.

[例如:

int  i;
typedef  int&  LRI;
typedef  int&&  RRI;

LRI&  r1  =  i; // r1 has the type int&
const  LRI&  r2  =  i; // r2 has the type int&
const  LRI&&  r3  =  i; // r3 has the type int&

RRI&  r4  =  i; // r4 has the type int&
RRI&&  r5  =  i; // r5 has the type int&&

decltype(r2)&  r6  =  i; // r6 has the type int&
decltype(r2)&&  r7  =  i; // r7 has the type int&
Run Code Online (Sandbox Code Playgroud)

- 结束例子]

来自部分[meta.trans.ref]:

template <class T> struct add_lvalue_reference; 如果T命名对象或函数类型,则成员typedef type 应命名T&; 否则,如果T名称类型为"rvalue reference to T1",则成员typedef type应命名T1&; 否则,类型应命名T.

它们完全是一回事.

在C++ 03中,它们也是一样的.来自[type.arg.type]:

如果template-parameter的template-argument T命名类型为" cv1的 引用S",则尝试创建类型" cv2的 引用T"会创建类型" cv12的 引用S",其中cv12是cv- quali firs cv1的并集cv2.冗余的cv-quali firs被忽略.

[例如:

template   < class  T >  class   X  {
void   f( const   T &);
/ ? . . . ? /
};
X< int & >  x;          / / X<int&>::f has the parameter type const  int&
Run Code Online (Sandbox Code Playgroud)

- 结束例子]