マイアプリには多数のIDが含まれています。私は最終的に他の人がコードを見ることができるようにしたいが、実行時のリバースエンジニアが容易に知られているIDを探すのは簡単ではない。また、開発中に、簡単なデバッグのためにログファイルに一定のIDを持たせると便利です。しかし、実行時には、これらのIDをReleaseコンパイル中に生成することでランダムにしたいと考えています。 <random>
のlibを使用する推奨されるコードは、下記のGetRandomId1()
に記載されています。 constexpr
はswitch文のようにコード内で使用できます。しかし、<random>
がconstexpr
に対応していないため、私の提案する機能でconstexpr
を使用することに問題があります。コンパイル時に乱数を生成する別の方法はありますか?あるいは、実行時に定数として使用されるコンパイル時に乱数を生成して、constexpr
という概念に反して考えていますか?コンパイル時に生成されたランダムIDでマジックID番号を置換する
#include <iostream>
#include <random>
// this is the code I would like to use to generate a random number at compile time
/*constexpr */int GetRandomId1()
{
std::random_device rd; // non-deterministic seed
std::mt19937 gen(rd()); // with constexpr uncommented:
// error C3250: 'rd': declaration is not allowed in 'constexpr' function body
// error C3249: illegal statement or sub-expression for 'constexpr' function
// error C3250: 'gen': declaration is not allowed in 'constexpr' function body
std::uniform_int_distribution<> distri(1000, 9999); // with constexpr uncommented:
// error C3250: 'distri': declaration is not allowed in 'constexpr' function bod
// error C3249: illegal statement or sub-expression for 'constexpr' function
// error C2134: 'std::uniform_int<_Ty>::operator()': call does not result in a constant expression
return distri(gen);
}
// this code is what works so far
constexpr int GetRandomId2()
{
return 22; // how to make somewhat random?
}
constexpr int AAA = 10;
//constexpr int AAA = GetRandonId1(); // error: is not constexpr function
constexpr int BBB = GetRandomId2(); // ok
void Func1(long ab)
{
switch(ab)
{
case AAA:
std::cout << AAA << std::endl;
break;
case BBB:
std::cout << BBB << std::endl;
break;
}
}
int main()
{
Func1(22); // ok: prints 22
return 0;
}
私はまっすぐ進む、私が提案したようなとHow can I generate dense unique type IDs at compile time?で提案されているテンプレートの多用とは異なり、保守ソリューションを探しています。またこの投稿で@jmihaliczaはRandom number generator for C++ template metaprograms研究論文を指しています。この論文では、IMO constexpr
が(私が言いましたか、あるいはしていたはずの)タスクを実現する複雑な試みである、テンプレートメタプログラミングを使用したコンパイル時の乱数生成について説明します。
アーキテクチャ上の理由から、私はIDの衝突について心配する必要がないので、心配はありません。アプリコードは、重複が返されないようにします。
ファイルに乱数を生成するカスタムビルド前のステップをいつでも追加することができます。 '#include'dになります – sp2danny