private std::string
C++ では、インスタンス シンボル名の文字列化/文字列化された名前で初期化されるデータ メンバーを持つクラスを宣言することは可能ですか? これは一時的には機能しないことがわかりますが、左辺値では可能ですか?
これが私が望むものです:
#include <iostream>
#include <string>
class symbol {
public:
symbol() { // here goes some magical sauce }
void print() { std::cout << s_ << std::endl; }
private:
std::string s_;
};
int main() {
symbol bar, bah;
bar.print() // should print "bar" to STDOUT
bah.print() // should print "bah" to STDOUT
}
文字列を受け入れるようにコンストラクターを変更し、プリプロセッサ マクロを導入すると、必要なものはほとんど得られますが、臭いがします。
#define makesymbol(x) foo x(#x)
symbol(const std::string & s) : s_(s) {}
// Now I can do:
makesymbol(test);
test.print(); // <--- This prints "test" followed by a newline to STDOUT
基本的に私が避けたいのは、ユーザーが次のようなシンボルのインスタンスを宣言する必要があることです:
symbol phi("phi");
読むのも入力するのも面倒で、冗長だからです。変数名とは異なる文字列を保存したい場合がある理由はわかりますが、文字列を文字列化された変数名と同じにしたいという問題を解決しようとしています。