gpt4 book ai didi

c++ - 原始类型的强 typedef (BOOST_STRONG_TYPEDEF 不会削减它)

转载 作者:行者123 更新时间:2023-12-03 12:49:07 24 4
gpt4 key购买 nike

我之前使用过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 的情况下无法比较或添加两种不同类型的对象。

  • 为什么会发生这种情况?
  • 如何在不为每种类型手动创建类的情况下实现基本类型的类型安全?

最佳答案

#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;
}

关于c++ - 原始类型的强 typedef (BOOST_STRONG_TYPEDEF 不会削减它),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47512925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com