启发使用C ++ 11 decltype [英] Enlightening Usage of C++11 decltype

查看:122
本文介绍了启发使用C ++ 11 decltype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚看过这个真的很棒的演讲 Rock Hard: C ++进化。在关于高阶通用编程的部分中,他说以下是关于其返回类型更通用的函数的示例,并且导致更少的模板函数重载

I've just seen this really nice talk Rock Hard: C++ Evolving by Boris Jabes. In the section of the talk concerning Higher-Order Generic Programming he says that the following is an example of a function that is more generic with regards to its return type and leads to fewer template function overloads

template <typename Func>
auto deduce(const Func & f) -> decltype(f())
{..}

模板语法如下

template <typename Func>
Func deduce(const Func & f)
{..}

因此我想所选择的示例不会真正显示 decltype 的独特功能。任何人都可以举例说明 decltype

so I guess the example chosen doesn't really show the unique power of decltype. Can anyone give an example of such a more enlightening usage of decltype?

推荐答案

您的怀疑不正确。

void f() { }

现在 deduce(& f)有类型 void ,它有类型 void(*)()。在任何情况下,无论你想要得到一个表达式或声明的类型,你使用 decltype (注意这两个之间的细微差别。 decltype (x)不一定与 decltype((x))相同。

Now deduce(&f) has type void, but with your rewrite, it has type void(*)(). In any case, everywhere you want to get the type of an expression or declaration, you use decltype (note the subtle difference in between these two. decltype(x) is not necessarily the same as decltype((x))).

例如,您的标准库实现可能包含

For example, it's likely your Standard library implementation somewhere contains lines like

using size_t = decltype(sizeof(0));
using ptrdiff_t = decltype((int*)0 - (int*)0);
using nullptr_t = decltype(nullptr);

查找添加的正确返回类型<一直是C ++过去一个具有挑战性的问题。这是一个简单的练习。

Finding out the correct return type of add has been a challenging problem throughout past C++. This is now an easy exercise.

template<typename A, typename B> 
auto add(A const& a, B const& b) -> decltype(a + b) { return a + b; }

很少有人知道您可以使用 decltype 之前 :: 和伪析构函数名称

Little known is that you can use decltype before :: and in a pseudo destructor name

// has no effect
(0).~decltype(0)();

// it and ite will be iterators into an initializer list 
auto x = { 1, 2, 3 };
decltype(x)::iterator it = x.begin(), ite = x.end();

这篇关于启发使用C ++ 11 decltype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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