[英]Strong typedef for primitive types (BOOST_STRONG_TYPEDEF is not cutting it)
我之前用过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;
}
前面的代码无法按预期编译:
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; }
但是,这段代码编译得很好:
#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;
}
}
这似乎一点都不强! 我希望在没有static_cast
情况下无法比较或添加两种不同类型的对象。
阅读http://www.boost.org/doc/libs/1_63_0/libs/serialization/doc/strong_typedef.html ,您使用 boost 的示例似乎可以编译,因为 boost 创建的类型可以替代原始类型,这些类型具有可比性.
来自fluentcpp 的Johnathan Boccara 在其github上提供了一个强类型的实现,这应该是你想要的:
#include <cassert>
#include "NamedType/named_type.hpp"
int main() {
using TIMER_ID =
fluent::NamedType<unsigned int, struct TimerIdTag, fluent::Comparable>;
using PROCESS_ID =
fluent::NamedType<unsigned int, struct ProcessIdTag, fluent::Comparable>;
TIMER_ID a(123);
PROCESS_ID b(456);
assert(a == a);
// assert(a == b); doesn't compile
return 0;
}
阅读http://www.boost.org/doc/libs/1_63_0/libs/serialization/doc/strong_typedef.html
该宏已经为您创建了新类。 您遇到的问题是转换完全按照设计工作(根据他们网站上的示例;也使用原始类型)。
我认为关于为什么他们的行为不同的问题是更有趣的问题; 但最终的答案似乎是,如果您需要此检查无法编译,这不是适合您的库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.