据我了解,您无法控制原始类型之间的隐式转换:它是标准强制要求的,任何兼容的编译器都会默默地执行它。
你确定像 BOOST_STRONG_TYPEDEF 这样的方法不能解决你的问题吗?一个没有虚成员函数而只有一个原始数据成员的类基本上只不过是一种 POD 数据类型。您可以遵循相同的方法,只允许转换为基本原始类型;例子:
#include <iostream>
#include <stdexcept>
struct controlled_int {
// allow creation from int
controlled_int(int x) : value_(x) { };
controlled_int& operator=(int x) { value_ = x; return *this; };
// disallow assignment from bool; you might want to use BOOST_STATIC_ASSERT instead
controlled_int& operator=(bool b) { throw std::logic_error("Invalid assignment of bool to controlled_int"); return *this; };
// creation from bool shouldn't happen silently
explicit controlled_int(bool b) : value_(b) { };
// conversion to int is allowed
operator int() { return value_; };
// conversion to bool errors out; you might want to use BOOST_STATIC_ASSERT instead
operator bool() { throw std::logic_error("Invalid conversion of controlled_int to bool"); };
private:
int value_;
};
int main()
{
controlled_int a(42);
// This errors out:
// bool b = a;
// This gives an error as well:
//a = true;
std::cout << "Size of controlled_int: " << sizeof(a) << std::endl;
std::cout << "Size of int: " << sizeof(int) << std::endl;
return 0;
}