【问题标题】:How to define an implicit conversion for typedefs?如何为 typedef 定义隐式转换?
【发布时间】:2020-03-29 18:03:00
【问题描述】:

我想将std::string 自动转换为我的类型my_type,定义为

typedef std::pair<std::string,int> my_type;

使得转换后的my_type.first 部分是字符串,而.second 部分始终为0。

如果调用函数std::string fun(my_type x, ...) { return x.first; } 时也应该可以使用,比如说,

std::string s = "Hello"; fun(s, ...);.

我不想定义一个新类来代替my_type,并且如果可能的话也不想重载我的所有函数。我试图围绕如何使用 operator 来解决这个问题,但我无法编译我的程序。

编辑: 由于如果不定义自定义结构左右这似乎是不可能的,这是我想出的一种解决方法,但我希望它可以在不定义新类/结构的情况下实现。不过,感谢您为我节省了更多尝试执行此操作的时间。

class Element {
  public:
    Element() {};
    Element(std::string s, int a) { name = s; value = a; };
    Element(std::string s) { name = s; value = 0; };
    ...
    std::string return_name() { return name; };
  private:
    std::string name;
    int value;
 };

std::string fun(Element x) { return x.return_name(); };

现在可以自动调用std::string s = "Hello"; fun(s);

【问题讨论】:

  • 做不到。寻找解决方法。
  • 您需要重载或使用转换运算符创建自己的类型。这些是唯一的选择。
  • “隐式类型转换”是一个矛盾。强制转换是您在源代码中编写的内容,用于告诉编译器进行转换。它总是明确的。您想要的术语是“隐式转换”。

标签: c++ casting


【解决方案1】:

无法为现有类添加新的隐式转换,例如std::pair。隐式转换只能是成员函数:

  • 可以用一个参数调用的非显式构造函数。如果有更多参数,则它们必须具有默认值。
  • operator T() const 转换运算符。

在不改变类定义的情况下,不可能向类添加新的成员函数。此限制是为了防止在全局或命名空间范围内引入的函数更改现有代码的语义。


您可以做的是创建一个带有转换构造函数的新类(可以用一个参数调用的非显式构造函数):

struct MyPair : std::pair<std::string, int> {
    // In this class scope pair now refers to std::pair<std::string, int>.

    MyPair(std::string const& a)
        : pair(a, 0)
    {}

    MyPair(pair const& a)
        : pair(a)
    {}
};

std::pair&lt;std::string, int&gt; 的派生使得通过 MyPair 成为可能,其中 std::pair&lt;std::string, int&gt; 是预期的。还有另一个将std::pair&lt;std::string, int&gt; 转换为MyPair 的构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    相关资源
    最近更新 更多