C++:如何区分对类成员的引用和对普通变量的引用?

标签 c++ c++11 rtti typetraits typeinfo

有没有什么办法可以判断一个引用变量是否引用了一个类成员(进而判断它属于哪个类)而不是一个普通的变量?这是一个简单的示例,希望能说明我的意思:

class A
{
    private:
        unsigned int x;

    public:
        A() : x(15) { }
        unsigned int& GetX() { return x; }
};

int main( void )
{
    A a;
    unsigned int y = 12;
    unsigned int& yr = y;
    unsigned int& xr = a.GetX();

    // Is there anyway of identifying, using typeid() or something
    // similar, whether xr refers to x inside class A or is its type
    // completely indistinguishable from that of yr? i.e. does its type
    // information contain anything along the lines of    
    // typeid(xr).name() == "A::unsigned int&" that identifies it as 
    // belonging to class A?

    return 0;
}

编辑:

No, there's no way to so distinguish. Why would you want to? Sounds suspiciously like an XY problem.

好吧,也许我的例子太简单了,也许我问的问题不对,所以让我给你一个更详细的例子:

考虑上面的 A 类。在大多数情况下,我只想使用 getter 方法来查询 x 的值,因此通常需要返回一个常量引用(在我的实际代码中,x 实际上是一个非常大的 vector 或矩阵,因此按值返回可能很慢) .但在某些特殊情况下,我可能希望能够更改 x 的值 - 即在用户指定的函数内部,该函数根据上一个问题绑定(bind)到函数包装器:C++: Generic function wrapper class as a member of a non-template class .因此,当将函数绑定(bind)到函数包装器时,将由用户函数修改的参数使用 getter 方法和辅助类提供,以删除 const 限定符,例如

A.BindFunc( UserFunc, WriteAccess::GetNonConstRef( A.GetX() ) );

WriteAccess 辅助类如下:

class WriteAccess
{
    public:

        template <typename T>
        static T& GetNonConstRef( const T& x )
        {
            return const_cast<T&>(x);
        }
};

用户提供的功能可能是:

void UserFunc( unsigned int& X )
{
    X = somethingelse;
}

但是,我想阻止 WriteAccess::GetNonConstRef() 方法与任何旧类成员一起使用,并且只允许它与类 A(和派生类)的成员一起使用).所以我想知道是否有办法在 WriteAccess::GetNonConstRef() 中确定所提供的引用属于哪个类,以便它不编译或者如果另一个类是终止执行用过。

所以我在想,如果有某种方法可以区分对普通变量的引用和类成员的引用(实际上是对类 A 成员的引用和对其他类成员的引用),那么这可能会对我有所帮助。

最佳答案

How to distinguish between a reference to a class member and a reference to an ordinary variable?

一般来说,这是不可能的。引用不包含对象容器的信息。子对象与独立对象无法区分。

typeid 不会有任何帮助。变量的完全限定名称不是变量类型名称的一部分。


但是,可以测试引用(或指针)是否指向特定容器实例的特定成员:

bool xr_refers_to_x_of_a = &xr == &a.GetX(); // true

关于C++:如何区分对类成员的引用和对普通变量的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42701964/

相关文章:

c++ - 在没有 RTTI 的情况下测试类型相等性

c++ - 为 'solver' 类设计通用处理程序

c++ - 错误 “no matching function for call ' begin(int [len] )' ”在我的代码中是什么意思?

c++ - move std::thread

delphi - 如何使用 rtti 访问类属性?

delphi - 使用 RTTI 方法调用返回的函数引用

C++ vector 旋转所有组合

c++ - 通过样式表识别特定的 QTabWidget 标签

c++ - 如何在 wxWidgets 中隐藏 wxListCtrl 的第一列?

c++11 - 识别 Eigen 中的临时对象创建