2011-07-26 40 views
9

我正在製作一個模板化類,它是任何迭代器的包裝器。我正在操作*這樣:Decltype函數返回

template <typename T> 
class MyIterator { 
public: 
    //... 
    decltype(*T()) operator*() { 
    //... 
    } 
} 

我給decltype一個調用到T級的運營商*,它甚至還可以,但是如果T可是沒有默認構造函數,它不會工作。

有無論如何找出返回的函數/方法的類型?

回答

16

這是std::declval是:

decltype(*std::declval<T>()) operator*() { /* ... */ } 

如果您實現不提供std::declval(的Visual C++ 2010不包括它),你可以輕鬆地寫自己:

template <typename T> 
typename std::add_rvalue_reference<T>::type declval(); // no definition required 

由於T是一個迭代器類型,您還可以使用std::iterator_traits模板,該模板不需要任何C++ 0x支持t:

typename std::iterator_traits<T>::reference operator*() { /* ... */ } 
+0

我的編譯器說「不能使用declval()」! –

+1

你的編譯器說的是什麼(以及你使用的編譯器是什麼?)你不能_ODR-use_'declval',因爲它沒有被定義;您只能在未評估的環境中「使用」它,例如在'decltype'中。 –

+0

/usr/lib/gcc/x86_64-unknown-linux-gnu/4.6.1/../../../../include/c++/4.6.1/type_traits:1134:7:error:static assertion失敗:「不能使用declval()!」 –