I doubt that what you want is a great idea, if you really insist, you could create a class that supports implicit conversion from char
, implicit conversion to std::string
, and can be compared with either another instance of itself or to a string:
class cvt {
char val;
public:
cvt(char val) : val(val) {}
bool operator<(cvt other) const { return val < other.val; }
bool operator<(std::string const &s) const {
return !s.empty() && val < s[0];
}
friend bool operator<(std::string const &s, cvt const &c) {
return !s.empty() && s[0] < c.val;
}
operator std::string() const { return std::string(1, val); }
};
With this, we can create our set<cvt>
, but use it as if it were a set<std::string>
(since the elements in it can/will convert to std::string
implicitly and compare with std::string
):
int main() {
std::string some_string = "ZABCDECD";
// Create our (sort of) set<string> from characters in some_string:
std::set<cvt> char_set(some_string.begin(), some_string.end());
// An actual set<string> to use with it:
std::set<std::string> strings{ "A", "C", "E", "F", "Y" };
// demonstrate compatibility:
std::set_intersection(char_set.begin(), char_set.end(), strings.begin(), strings.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
Live on Coliru.
If we look at the generated code for this on Godbolt, we see that it really is nearly all syntactic sugar--the only code that's actually generated for the cvt
class are the tiny bits to copy a byte in to create a cvt
from a char
, and to compare a cvt
to a string
. Everything else has been optimized out of existence.
If we're sure our strings won't be empty, we can simplify the comparisons to return val < s[0];
and return s[0] < val;
, in which case they get optimized away as well, so the only code that's generated from using cvt
is a copying a byte from the source to construct a cvt
object.
Depending on what you have in mind, that might fit what you want. It's a fair amount of extra typing, but it optimizes nicely--to the point that it's probably faster to compare a cvt
to a string than to compare a string
to a string
. By far the largest disadvantage is likely to stem from questioning your basic premise, and wondering why you wouldn't just write a loop and be done with it.