2013-07-15 23 views
1

我有以下功能的boost ::獲得提振::變異沒有給予正確的輸出

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*)轉換爲boolstd::string所以你的字符串字面量不初始化變種的string成分更好,但不是bool組件(真)。

查看哪些輸出bool 1如下:

#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")初始化將解決你的問題。

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

2

這裏發生的事情是因爲在boost :: variant中存在一個bool,所以你傳遞的const char *不再用於字符串,而是轉換爲bool。

,如果你改變這一行:

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

這樣:

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

它會奏效。

這就是爲什麼bool被選中的字符串:隱式轉換髮生在任何類型的指針和布爾之間,並且內置類型之間的轉換始終優於用戶定義的轉換。由於std :: string是一個用戶定義的類型(標準介意你,但仍然是用戶定義的),bool勝過字符串。