2017-11-27 10 views
0

내가 주로 std::string로, 이전 BOOST_STRONG_TYPEDEF을 사용하고 내가 만족스러운 결과를 얻었다 :강력한 형식 정의 (BOOST_STRONG_TYPEDEF가 절단되지 않음)

#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없이 두 가지 유형의 객체를 비교하거나 추가 할 수 없기를 기대합니다.

  • 왜 이런 일이 발생합니까?
  • 각 유형에 대한 클래스를 수동으로 생성하지 않고도 기본 유형으로 유형 안전성을 달성하려면 어떻게해야합니까?
+1

우리는 CUJ의 Matthew Wilson의 '진정한 typedef'를 사용합니다 : http://www.drdobbs.com/true-typedefs/184401633. 이 토론 (https://stackoverflow.com/questions/23726038/how-can-i-create-a-new-primitive-type-using-c11-style-strong-typedefs 및 http : // boost-users)도 참조하십시오. boost.narkive.com/XVDlErPB/boost-strong-typedef. – gast128

답변

0

http://www.boost.org/doc/libs/1_63_0/libs/serialization/doc/strong_typedef.html

읽기 매크로는 이미 당신을 위해 새로운 클래스를 생성합니다. 당신이 가지고있는 문제는 전환이 (사이트의 예제에 따라) 기본으로 사용되는 것과 똑같이 설계된대로 작동한다는 것입니다.

왜 다른 행동이 다른지에 대한 질문은 더 흥미로운 질문이라고 생각합니다. 하지만 궁극적으로 대답은이 수표가 컴파일되지 않으면 라이브러리가 아닌 것 같습니다.

+0

답변 주셔서 감사합니다. 그러나 실제로 내 질문에는 답변이 없습니다. 어떤 대안이 있는지 아십니까? – user2891462

+0

@ user2891462 나는 두려워하지 않는다. 나는 '명백한'키워드를 충분히 응용하여 내 자신을 쓸 것이다. 오늘 밤으로 돌아와서 내가 왜 다른 이유인지 알아낼 수 있을지 모르지만, 당신이하고 싶은 일에서 당신을 도울 방법이 없을 것입니다. – UKMonkey