【发布时间】:2017-03-10 02:38:47
【问题描述】:
有没有可能的方法来判断一个引用变量是否引用了一个类成员(然后判断它属于哪个类)而不是一个普通的变量?这是一个简单的例子,希望能说明我的意思:
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;
}
编辑:
不,没有办法如此区分。你为什么想要?声音 有点像 XY 问题。
好吧,也许我的例子太简单了,也许我没有问对问题,所以让我给你一个更详细的例子:
考虑上面的A类。在大多数情况下,我想使用 getter 方法来查询 x 的值,因此通常需要返回一个常量引用(在我的实际代码中,x 实际上是一个非常大的向量或矩阵,因此按值返回可能会很慢) .但在某些特殊情况下,我可能希望能够更改 x 的值 - 即在用户指定的函数内部,该函数根据之前的问题绑定到函数包装器:C++: Generic function wrapper class as a member of a non-template class。因此,当将函数绑定到函数包装器时,将由用户函数修改的参数使用 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 类成员的引用和对其他类成员的引用),那么这可能会对我有所帮助。
【问题讨论】:
-
不,没有办法如此区分。你为什么想要?听起来很像an XY problem。
-
添加
int& A::GetX()似乎更简单... -
顺便说一句,你可能有
const int& ref = cond ? y : a.GetX(); -
您是否考虑过只创建一个返回非常量引用的 Getter 并使用它而不是创建一个删除 const 的函数?
-
@Kian 好吧,当然。但这太容易了不是吗? ;)
标签: c++ c++11 rtti typetraits typeinfo