返回函数的Decltype [英] Decltype for return of a function

查看:80
本文介绍了返回函数的Decltype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个模板类,该类是任何迭代器的包装。我是这样操作的*:

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

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

我给decltype调用了T类的操作符*,它甚至可以工作,但是如果T没有默认的构造函数,它将无法工作。

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 ?

推荐答案

这是 std :: declval 的作用:

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

如果您的实现未提供 std :: declval (Visual C ++ 2010不提供)包括它),您可以轻松自己编写:

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






由于 T 是迭代器类型,您还可以使用 std :: iterator_traits 模板,该模板不需要任何C ++ 0x支持:


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*() { /* ... */ }

这篇关于返回函数的Decltype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆