2011-06-02 48 views
8

我通過"C++ Template Metaprogramming" by Abrahams & Gurtovoy工作「 這實際上不是在第二章,但是是我嘗試過,而在第一次演練工作(2.10,2.0),這是混淆了我:爲什麼boost :: is_same <int const&,boost :: add_const <int &> :: value等於false?

#include <iostream> 
#include <boost/type_traits.hpp> 

std::string display(bool b) 
{ 
    return (b ? "true" : "false"); 
} 

int main() 
{ 
    using namespace std; 

    cout << display(boost::is_same<int const&, boost::add_const<int &>::type >::value) << "\n"; 

    return 0; 
} 

輸出爲' false' 但是,如果我刪除了引用,即'int const'和'int'。輸出爲'true'。

+3

順便說一句你可以通過設置'std :: cout << std :: boolalpha;' – juanchopanza 2011-06-02 16:51:34

回答

11

如果你試圖用三分球一樣的東西,如

boost::is_same<int const *, boost::add_const<int *>::type>::value 

你會發現,這也是假的,因爲boost::add_const<int *>::type產生int *const型,這顯然是不一樣的int const *

基本上同樣的事情發生在參考文獻中,即boost::add_const<int &>::type是試圖產生int &const。形式上,類型int &const在C++中是非法的 - cv-qualification不能應用於引用本身。因此,boost::add_const被設計爲在這種情況下爲空操作,這意味着boost::add_const<int &>::type再次生成int &

+0

我現在明白了。我認爲add_const 會給我int const&但它會嘗試添加const *另一邊*,謝謝 – 2011-06-02 21:22:55

9

您不能將const添加到引用,它將是int& const這是不可能的。

就像使用typedef一樣,添加q ualifiers不是文本替代品,而是適用於整個類型的東西。

+0

來避免你的'顯示'函數的含義是(如果不明確)'boost :: add_const :: type '仍然只是'int&'。 – ildjarn 2011-06-02 16:43:24

+0

如正式文檔的示例所示:http://www.boost.org/doc/libs/1_46_1/libs/type_traits/doc/html/boost_typetraits/reference/add_const.html – 2011-06-02 16:44:37

+0

實際上'int&const'是非法的。如果允許的話,這將是多餘的,因爲一個引用已經隱式地const了。 – 2011-06-02 16:53:15

相關問題