1

乱数を生成したい単純な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'を'result_typestd :: tr1 ::mersenne_twister <_UIntType、__w、__ n、__ m、__r、__a、__u、__s、__b、__t、__cの'this'引数として渡す__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 unsignedint]'は修飾子を破棄します

const_castこれはオンなしで実行できthisますか?

4

1 に答える 1

1

mersenne_twisterオブジェクトをクラス内で変更可能にします。すべてのコード(特にdo_somethingの部分)を確認しないと、確信が持てませんが、merseene_twister型のクラス内に、const関数自体ではない関数を使用しているオブジェクトがあると思います。 。これにより、クラスでエラーが発生します。これは、const関数がmerseen_twisterで関数を呼び出して、それを変更し、constシグネチャに違反している可能性があるためです。

// I'm using this as an example.  Yours may differ
typedef std::mersenne_twister<unsigned int, 32, 624, 
    397, 31, 0x9908b0df, 11, 7, 0x9d2c5680, 
    15, 0xefc60000, 18> MerTwister;

class Object 
{
    public:

    int Object::const_method() const 
    {
       std::tr1::uniform_int<int> uni(0,100);

       // do some calculation using the MerTwister object
       return result;
    }


    private:
    mutable MerTwister twister;
};
于 2010-11-15T00:06:46.240 に答える