问题描述
我刚看过 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);
查找添加
的正确返回类型
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!