Reputation: 10539
I have code similar to this:
class Pair{
public:
Pair(const void *blob);
//...
int cmp(const std::string &key) const;
int cmp(const Pair &pair) const;
}
Later if I do:
Pair p = ...;
p.cmp("Hello");
It won't compile, because conversion from const char *
is ambiguous.
It can be translated to std::string
and cmp(std::string)
to be invoked, or...
it can be translated to Pair
and cmp(const Pair)
to be invoked.
I can not do constructor explicit
.
I tried to do:
Pair(const char *blob) = deleted;
But then I can not construct the class with nullptr
and I want to be able to do so.
As final solution, I defined following method:
int cmp(const char *key) const{
return cmp( std::string{ key } );
}
and it works fine.
Is there better way to deal with such class conversions?
Upvotes: 2
Views: 124
Reputation: 25409
Your “final solution” looks pretty good to me. Not constructing a temporary will also help improve performance. If your strings are known not to contain NUL characters, you can implement the version taking a std::string
as argument as
inline int
cmp(const std::string& s)
{
return this->cmp(s.c_str());
}
which is too simple to worry about.
Making Pair
's constructor explicit
(I assume the “implicit
” is a typo) sounds a good idea to me, too. Why can't you do it?
Upvotes: 4
Reputation: 206577
You can make the constructor explicit
.
explicit Pair(const void *blob) { ... }
Then,
p.cmp("Hello");
will resolve to
int cmp(const std::string &key) const;
Upvotes: 2