I have used BOOST_STRONG_TYPEDEF
before, mainly with std::string
and I got satisfactory results:
我之前使用过BOOST_STRONG_TYPEDEF,主要使用std :: string,我得到了满意的结果:
#include <boost/serialization/strong_typedef.hpp>
#include <iostream>
BOOST_STRONG_TYPEDEF(std::string, TIMER_ID)
BOOST_STRONG_TYPEDEF(std::string, PROCESS_ID)
int main()
{
TIMER_ID t_id("Timer");
PROCESS_ID p_id("Process");
if (t_id == p_id)
std::cout << "They are equal!" << std::endl;
}
The previous code fails to compile as expected:
以前的代码无法按预期编译:
In file included from /usr/include/boost/serialization/strong_typedef.hpp:26:0,
from types.cpp:1:
/usr/include/boost/operators.hpp: In instantiation of ‘bool boost::operator==(const std::__cxx11::basic_string<char>&, const PROCESS_ID&)’:
types.cpp:12:14: required from here
/usr/include/boost/operators.hpp:144:64: error: no match for ‘operator==’ (operand types are ‘const PROCESS_ID’ and ‘const std::__cxx11::basic_string<char>’)
friend bool operator==(const U& y, const T& x) { return x == y; }
However, this code compiles just fine:
但是,这段代码编译得很好:
#include <boost/serialization/strong_typedef.hpp>
#include <iostream>
BOOST_STRONG_TYPEDEF(unsigned int, TIMER_ID)
BOOST_STRONG_TYPEDEF(unsigned int, PROCESS_ID)
int main()
{
TIMER_ID t_id(12);
PROCESS_ID p_id(12);
if (t_id == p_id)
{
std::cout << "They are equal!" << std::endl;
std::cout << "Their sum is " << t_id + p_id << std::endl;
}
}
This doesn't seem strong at all! I would expect to not be able to compare or add objects of two different types without a static_cast
.
这看起来并不强大!如果没有static_cast,我希望无法比较或添加两种不同类型的对象。
- Why is this happening?
- How can one accomplish type safety with primitive types without manually creating classes for each type?
为什么会这样?
如何在不为每种类型手动创建类的情况下使用基本类型实现类型安全?
1 个解决方案
#1
0
Reading http://www.boost.org/doc/libs/1_63_0/libs/serialization/doc/strong_typedef.html
The macro creates new classes for you already. The problem that you're having is that the conversion is working exactly as designed (as per the examples on their site; which also use primitive types).
宏已经为您创建了新类。您遇到的问题是转换完全按照设计工作(根据其网站上的示例;它们也使用基本类型)。
I think the question about why they're different behaviors is different is the more interesting one; but ultimately the answer seems to be this isn't the library for you if you require this check to fail to compile.
我认为关于他们为什么不同的行为不同的问题是更有趣的问题;但最终答案似乎是,如果您需要此检查无法编译,这不是您的库。
#1
0
Reading http://www.boost.org/doc/libs/1_63_0/libs/serialization/doc/strong_typedef.html
The macro creates new classes for you already. The problem that you're having is that the conversion is working exactly as designed (as per the examples on their site; which also use primitive types).
宏已经为您创建了新类。您遇到的问题是转换完全按照设计工作(根据其网站上的示例;它们也使用基本类型)。
I think the question about why they're different behaviors is different is the more interesting one; but ultimately the answer seems to be this isn't the library for you if you require this check to fail to compile.
我认为关于他们为什么不同的行为不同的问题是更有趣的问题;但最终答案似乎是,如果您需要此检查无法编译,这不是您的库。