C++ TR1:在 const 方法中使用均匀分布生成随机数的正确方法是什么?
我有一个简单的 const 方法想要生成一个随机数
int Object::const_method() const {
std::tr1::uniform_int<int> uni(0,100);
// do some calculation
return result;
}
这会导致您的标准(如果模板化)const 违规错误
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.5.1/../../../../include/c++/4.5.1/tr1/random.tcc:910: 4: 错误:传递 'const std::tr1::mersenne_twister' 作为 'this' 参数 '结果类型 std::tr1::mersenne_twister<_UIntType, __w、__n、__m、__r、__a、__u、__s、__b、__t、__c、__l>::operator()() [其中 _UIntType = long unsigned int, int __w = 32,int __n = 624,int __m = 397、int __r = 31、_UIntType __a = 2567483615ul,int __u = 11,int __s = 7、_UIntType__b=2636928640ul,int __t = 15,_UIntType __c = 4022730752ul,int __l = 18, result_type = long unsigned int]' 丢弃限定符
如果 this
上没有 const_cast
,这是否可行?
I have a simple const method that wants to generate a random number
int Object::const_method() const {
std::tr1::uniform_int<int> uni(0,100);
// do some calculation
return result;
}
This results in your standard (if templafied) const violation error
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.5.1/../../../../include/c++/4.5.1/tr1/random.tcc:910:4:
error: passing ‘const
std::tr1::mersenne_twister’ as ‘this’ argument
of ‘result_type
std::tr1::mersenne_twister<_UIntType,
__w, __n, __m, __r, __a, __u, __s, __b, __t, __c, __l>::operator()() [with _UIntType = long unsigned int,
int __w = 32, int __n = 624, int __m =
397, int __r = 31, _UIntType __a =
2567483615ul, int __u = 11, int __s =
7, _UIntType __b = 2636928640ul, int
__t = 15, _UIntType __c = 4022730752ul, int __l = 18,
result_type = long unsigned int]’
discards qualifiers
Is this doable without a const_cast
on this
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使 mersenne_twister 对象在类中可变。如果没有看到您的所有代码(尤其是 do_something 部分),我们无法确定,但我猜测您的类中有一个 merseene_twister 类型的对象,您正在使用的函数本身不是 const 函数。这会导致您的类中出现错误,因为您的 const 函数正在调用 merseen_twister 上的一个函数,该函数可能会更改它,从而违反了您的 const 签名。
Make your mersenne_twister object mutable within your class. Without seeing all your code, (especially the do_something part), we can't be certain, but I'm guessing that you have an object within your class of type merseene_twister which you are using a function of which is not a const function itself. This is causing the error in your class, because your const function is calling a function on merseen_twister that may change it, violating your const signature.