0

作为一个 C++ 初学者,我想写一些简单的类型转换。有没有办法创建可以在type new = (type)old带有前缀括号的格式中使用的转换逻辑?

string Text = "Hello";
char* Chars = "Goodbye";
int Integer = 42;

string Message = Text + (string)Integer + (string)Chars + "!";

如果可能的话,我想坚持使用这种语法。例如,boost 的字符串转换int Number = boost::lexical_cast<int>("Hello World")有一个没有吸引力的长语法。

4

2 回答 2

2

只需使用为不同类型重载的普通函数:

std::string str(int i) {
   return "an integer";
}

std::string str(char* s) {
   return std::string(s);
}

然后使用 if 不像强制转换,而是作为普通函数调用:

string Message = Text + str(Integer) + str(Chars) + "!";
于 2012-08-25T13:23:18.710 回答
1

NAME<TYPE>(ARGUMENT)使用语法进行转换是 C++ 中最常见的事情,例如在static_cast<int>(char). 以 boost 的方式扩展它是有意义的。

但是,如果要转换非原始类型,可以使用带有单个参数和强制转换运算符的非显式构造函数。

class MyType {
  public:
    MyType(int); // cast from int
    operator int() const; // cast to int
};

如果您正在处理已经存在的类型,这是不可能的。

您无法更改 C 样式转换的行为。C++ 将决定如何解释这样的转换。

但是,您可以提出一种缩短语法的中间类型:

template <typename From>
struct Cast {
  From from;
  Cast(From const& from) : from(from) {}
  template <typename To>
  operator To() const {
    return convert(from,To());
  }
};

template <typename From>
Cast<From> cast(From const& from) {
  return Cast<From>(from);
};

std::string convert(int, std::string const&);

这将允许您明确地转换事物,但不说明具体如何:

int i = 7;
std::string s = cast(i);
于 2012-08-25T13:23:06.510 回答