什么是处理模糊类型转换/转换的正确方法C ++ 11

时间:2015-09-14 20:42:01

标签: c++ c++11 casting

我的代码类似于:

class Pair{
public:
    Pair(const void *blob);
    //...
    int cmp(const std::string &key) const;
    int cmp(const Pair &pair) const;
}

稍后如果我这样做:

Pair p = ...;
p.cmp("Hello");

它无法编译,因为来自const char *的转换不明确。

可以将其翻译为std::stringcmp(std::string)来调用,或者......

可以将其翻译为Paircmp(const Pair)来调用。

我不能做构造函数explicit

我试着这样做:

Pair(const char *blob) = deleted;

但是我不能用nullptr构建这个类,我希望能够这样做。

作为最终解决方案,我定义了以下方法:

int cmp(const char *key) const{
   return cmp( std::string{ key } );
}

它工作正常。

是否有更好的方法来处理此类转换?

2 个答案:

答案 0 :(得分:4)

你的“最终解决方案”对我来说非常好。不构建临时性也有助于提高性能。如果已知您的字符串不包含NUL字符,则可以将inline int cmp(const std::string& s) { return this->cmp(s.c_str()); } 作为参数实现为

Pair

太容易担心了。

制作explicit的构造函数implicit(我认为“{{1}}”是一个错字)对我来说听起来也不错。你为什么不能这样做?

答案 1 :(得分:3)

您可以制作构造函数explicit

explicit Pair(const void *blob) { ... }

然后,

p.cmp("Hello");

将解析为

int cmp(const std::string &key) const;
相关问题