2013-07-15 4 views
1

을 제공하지 I가 다음과 같은 기능부스트 :: 향상 얻을 :: 변형은 더 정확한 출력

template <typename T, typename U> 
const T* visitor_fct(U& operand) 
{ 
    return (boost::get<T>(&operand)); 
} 

내가

boost::variant<int, std::string> str = "string"; 
std::cout << visitor_fct<std::string>(str) << std::endl; 

내가 올바른 출력을 얻을 할 때

그러나 때 내가 str의 선언을 다음과 같이 변경하십시오.

boost::variant<int, std::string, bool> str = "toto";

나는 항상 nullptr을 얻고있다;

왜?

답변

2

이유는 문자열 리터럴 (char*)는 변형의 string 구성 요소를 초기화하지 않습니다 그래서 당신의 문자열 리터럴 std::string보다 bool 더 나은 변환 만이 아니라 bool 구성 요소 (True로)이다.

#include <iostream> 

void foo(bool b) 
{ 
    std::cout << "bool " << b << std::endl; 
} 

void foo(std::string s) 
{ 
    std::cout << "string " << s << std::endl; 
} 

int main() 
{ 
    foo("Bar"); 
} 

std::string("toto")으로 초기화 문제를 해결할 수 :

bool 1 출력은 다음을 참조하십시오.

4.12/1

우리에게 해당 변환을 보여준다

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a 
prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; 
any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of 
type bool; the resulting value is false. 

이 암시 적 변환이 사용 유형을 일으키는 선택된 그래서 std::string의 변환 생성자보다 우선하고 [다른 않음에도 바와 같이] 변형에서 bool이됩니다. 부스트 :: 변형에서 부울 존재, 당신은 오히려 더 이상 문자열에 사용되지만 통과하지거야 * CONST 숯불 부울로 변환되고이 때문에 여기에서 일어나고있는 것 같다 무엇

2

이다. 이것에

boost::variant<int, std::string, bool> str = "toto"; 

:이 라인을 변경하는 경우

boost::variant<int, std::string, bool> str = std::string("toto"); 

이 작동합니다. 부울 문자열을 통해 선택됩니다 왜

은 다음과 같습니다 암시 적 변환은 포인터와 부울 어떤 종류의 사이에 발생하고, 내장 타입 항상 사용자 정의 변환에 선호된다 간의 변환. 그리고 std :: string은 사용자가 정의한 유형이므로 (표준 마음은 있지만 여전히 사용자 정의) bool은 문자열을 이깁니다.