我正在尝试包装一个对象,并希望将其作为指向函数的指针传递。已知该对象可以强制转换为有限类型,而我想为这些类型提供强制转换运算符。例如:
class MyInt {
public:
MyInt() {}
MyInt(int val): int32_storage_(val), int64_storage_(val*2) {}
const int32_t* GetInt32Ptr() const { return &int32_storage_; }
const int64_t* GetInt64Ptr() const { return &int64_storage_; }
private:
int32_t int32_storage_ = 0;
int64_t int64_storage_ = 0;
};
int32_t int32_add(const int32_t* iptr_a, const int32_t* const iptr_b) {
return *iptr_a + *iptr_b;
}
int64_t int64_add(const int64_t* iptr_a, const int64_t* const iptr_b) {
return *iptr_a + *iptr_b;
}
int main() {
MyInt a(10);
MyInt b(20);
std::cout << "32bit a + b = " << int32_add(a.GetInt32Ptr(), b.GetInt32Ptr()) << std::endl;
std::cout << "64bit a + b = " << int64_add(a.GetInt64Ptr(), b.GetInt64Ptr()) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的预期是,以取代GetInt32Ptr()与铸造运营商,所以我可以调用int32_add()这样int32_add(&a, &b)。我试过了
const int32_t*() const { return &int32_storage_; }
const int64_t*() const { return &int64_storage_; }
Run Code Online (Sandbox Code Playgroud)
但这不起作用。
您快到了,运算符定义的正确语法是:
operator const int32_t*() const { return &int32_storage_; }
operator const int64_t*() const { return &int64_storage_; }
Run Code Online (Sandbox Code Playgroud)
还要注意的是所描述的在这里,你还可以让这些运营商explicit,这往往需要保护网络免受不必要的转换。进行转换时,它需要更多的详细信息,例如,static_cast<const int32_t*>(a)而不是just a。
当您希望该类型隐式转换为另一种类型时,您必须将其声明为方法operator:
operator const int32_t*() const { return &int32_storage_; }
operator const int64_t*() const { return &int64_storage_; }
Run Code Online (Sandbox Code Playgroud)
现在,为了调用这些函数,只需说a, b它们就会被隐式转换:
std::cout << "32bit a + b = " << int32_add(a, b) << std::endl;
std::cout << "32bit a + b = " << int64_add(a, b) << std::endl;
Run Code Online (Sandbox Code Playgroud)
注意:您的函数限定符不一致 ( const int32_t*)
他们都应该是const T* const
也std::endl一般是错误的,将其替换为'\n'-推理