C++ 基本类型的强typedef(BOOST_Strong_typedef没有剪切它)

C++ 基本类型的强typedef(BOOST_Strong_typedef没有剪切它),c++,boost,type-safety,C++,Boost,Type Safety,我以前使用过BOOST\u STRONG\u 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() { TIM

我以前使用过
BOOST\u STRONG\u 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;
}
#包括
#包括
BOOST_STRONG_TYPEDEF(标准::字符串,计时器ID)
BOOST_STRONG_TYPEDEF(标准::字符串,进程ID)
int main()
{
计时器ID t_ID(“计时器”);
过程ID p_ID(“过程”);
if(t_id==p_id)
标准::cout读数

宏已经为您创建了新类。您遇到的问题是转换工作完全按照设计进行(根据他们网站上的示例;它们也使用基本类型)

我认为关于为什么它们的行为不同的问题更有趣;但最终的答案似乎是,如果您要求此检查无法编译,则此库不适合您。

  • 阅读 ,您使用boost的示例似乎可以编译,因为boost创建的类型可以替换为可比较的原始类型

  • 来自的Johnathan Boccara在its上提供了强类型的实现,这应该是您想要的:

#包括
#包括“NamedType/named_type.hpp”
int main(){
使用计时器ID=
fluent::NamedType;
使用进程ID=
fluent::NamedType;
定时器识别号a(123);
过程标识b(456);
断言(a==a);
//断言(a==b);不编译
返回0;
}

我们使用了来自CUJ的Matthew Wilson的“true typedef:。另请参阅此讨论和。感谢您的回答,但它并没有真正回答我的任何问题。您知道其他选择吗?@user2891462恐怕不知道,我会使用大量的“explicit”关键字来编写我自己的。今晚我可能有机会回到这里来讨论一下如果我能找出它不同的原因,但它可能对你想做的事情没有任何帮助。
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;
    }
}
#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;
}