簡體   English   中英

原始類型的強類型定義(BOOST_STRONG_TYPEDEF 沒有削減它)

[英]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情況下無法比較或添加兩種不同類型的對象。

  • 為什么會這樣?
  • 如何在不為每種類型手動創建類的情況下使用原始類型實現類型安全?
#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM