开发者

Decltype for return of a function

开发者 https://www.devze.com 2023-03-22 22:17 出处:网络
I am making a templated class that is a wrapper around any iterator. I am making the operator* this way:

I am making a templated class that is a wrapper around any iterator. I am making the operator* this way:

template <typename T&g开发者_JS百科t;
class MyIterator {
public:
    //...
    decltype(*T()) operator*() {
    //...
    }
}

I give decltype a invocation to operator* of class T, and it even works, but if T doesnt have default constructor it wont work.

Is there anyway to find out the returned type of a function/method ?


This is what std::declval is for:

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

If your implementation does not provide std::declval (Visual C++ 2010 does not include it), you can easily write it yourself:

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

Since T is an iterator type, you could also use the std::iterator_traits template, which does not require any C++0x support:

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

精彩评论

暂无评论...
验证码 换一张
取 消