2010-01-10 81 views
2

我想使用類型特徵來添加對模板參數的引用。boost add_reference不能使用模板參數

template < class T > 
struct S { 
typename add_reference<T>::type reference; // reference member should always be a reference 
}; 
... 
typedef Bar<Foo> type; 
S<type> s; // does not add reference, S:: reference is of type type, not type& 

但是它似乎並不奏效。這是正確的做法嗎?我的編譯器是g ++ 4.3。 謝謝。

說明:無論是S < type>還是S <類型&>,我都希望引用成員作爲參考。

回答

7

您忘記了typedeftypename只是說你要使用一個在模板聲明的時候還沒有被稱爲類型的類型名。如果你真的想創建一個typedef,那麼你實際上需要這個關鍵字。而且我認爲你忘了在下面使用它時實際上命名該類型:

template < class T > 
struct S { 
    typedef typename add_reference<T>::type reference; 
}; 
... 
typedef Bar<Foo> type; 
S<type>::reference s = some_foo; // initialize! 

請記住初始化引用。如果你事先知道T從來都不是一個參考(避免引用到引用的問題),你也可以直接做到這一點:

template < class T > 
struct S { 
    typedef T &reference; 
}; 

typedef Bar<Foo> type; 
S<type>::reference s = some_bar_foo; // initialize! 

如果你想要做的是創造一個參考的數據成員,你的語法沒有typedef是正確的

template < class T > 
struct S { 
    typename add_reference<T>::type reference; 
}; 
... 
typedef Bar<Foo> type; 
S<type> s = { some_bar_foo }; // initialize! 
s.reference = some_other_bar_foo; // assign "some_other_bar_foo" to "some_bar_foo" 

我不知道你想要做什麼。

+0

哦,是的,我沒有看到缺少「typedef」。當然也是如此:) – 2010-01-10 20:46:46

+0

我曾希望引用成員始終是引用,不管S是否實例化爲S 或S 。它是第一個不起作用的引用成員。 add_reference不會爲創建參考 – Anycorn 2010-01-10 20:52:05