假设我有一个存储一些数据的类,
class Value {
public:
enum class Type {
int_type,
float_type,
double_type,
bool_type
};
friend bool operator==(const Value& lhs, const Value& rhs) {
// how to make this function clean and concise?
}
private:
void* ptr;
Type type;
};
Run Code Online (Sandbox Code Playgroud)
ptr指向基础值并type指示ptr应如何转换。
为了比较Value对象,我绝对可以列出所有可能的类型组合,但是代码将很难维护。喜欢:
if (lhs.type == Type::int_type && rhs.type == Type::float_type) {
return *static_cast<int*>(lhs.ptr) == *static_cast<float*>(rhs.type);
}
Run Code Online (Sandbox Code Playgroud)
任何想法如何减少复杂性?
更新:
我希望此类为动态类型,这意味着我可以执行以下操作:
Value v("abc"); // v is now a string
v = 123; // v is …Run Code Online (Sandbox Code Playgroud) 以下代码:
package main
import "fmt"
func main() {
str := "s"
for i, v := range str {
fmt.Printf("type of s[%v]: %T\n", i, str[i])
fmt.Printf("type of v: %T\n", v)
}
}
Run Code Online (Sandbox Code Playgroud)
收益率:
type of s[0]: uint8
type of v: int32
Run Code Online (Sandbox Code Playgroud)
在大多数语言中,字符串由有符号或无符号的8位字符组成.为什么v int32而不是uint8?
假设 IR 代码如下所示:
define void @_Z1mbb(i1 zeroext %r, i1 zeroext %y) nounwind {
entry:
%r.addr = alloca i8, align 1
%y.addr = alloca i8, align 1
%l = alloca i8, align 1
%frombool = zext i1 %r to i8
store i8 %frombool, i8* %r.addr, align 1
%frombool1 = zext i1 %y to i8
store i8 %frombool1, i8* %y.addr, align 1
%0 = load i8* %y.addr, align 1
%tobool = trunc i8 %0 to i1
br i1 %tobool, label %lor.end, label …Run Code Online (Sandbox Code Playgroud)