さまざまなコンテナー (char*、std::string、カスタム文字列型) と形式 (utf-8、utf-16、utf-32) で文字列を必要とするインターフェイスの組み合わせが悪いため、文字列を変換するためのユーティリティを作成しようとしています。 . そこで、さまざまな型へのキャスト演算子を使用してラッパーを作成するというアイデアがありました。このような:
#include <iostream>
#include <string>
struct X {
operator std::string() { return std::string("string x"); }
operator const char *() { return "zstring x"; }
};
X make_x() { return X(); }
int main()
{
std::string y = make_x(); // this works
std::string y(make_x()); // but this does not
y = make_x(); // this does not work either
y = std::string(make_x()); // nor does this, so it's about useless
std::cout << y << std::endl;
return 0;
}
char *
しかし問題は、型が と の両方に変換される場合std::string
、std::string
コンストラクターと代入がこれら 2 つの型の間であいまいになることです。またchar *
、文字列は最初に nul で終了するのではなく範囲で指定される可能性があるため、単に .
それで、これらを明確にする方法はありますか?
重要な注意: 私はいくつかの C++03 コンパイラで立ち往生しているため、どちらのキャスト演算子も明示的にマークすることはできません。