【译】VC10中的C++0x特性 part 3 : 声明之类型

 

译】VC10 中的 C++0x 特性 part 3 : 声明之类型 

原文来源:vcblog 翻译:罗朝辉 (http://www.cnblogs.com/kesalin/
本文遵循“署名-非商业用途-保持一致”创作公用协议

 

简介 

这一系列文章介绍Microsoft Visual Studio 2010 中支持的C++ 0x特性,目前有三部分。 
Part 1 :介绍了Lambdas, 赋予新意义的auto,以及 static_assert; 
Part 2( 1 , 2 ):介绍了右值引用(Rvalue References); 
Part 3 :介绍了表达式类型(decltype)

VC10中的C++0x特性 Part 1,2,3 译文打包下载(doc 和 pdf 格式): 点此下载

本文是Part 3。

 

今天我要讲 decltype ,它让完美转发函数能够返回任意类型的东西。 对编写高度泛型的人来说这是很有趣的的特性。

 

返回问题

C++98/03 有一个有意思的盲点: 给定一个像 x * y 的表达式, 和 是任意类型,你却没法知道 x * y 的类型。假如 是 Watts 类型的, 是 Seconds 类型的,那 x * y 的类型可能会是 Joules 类型的。 给定声明 print(const T& t) , 调用 print( x * y ) ,在这里 会被推 导为 Joules 类型。但反 过 来却不是这样的:当你写个函数 multiply(const A& a, const B& b) ,你无法指定它的通用返回类型。即使是 实 例化成 multiply<A, B>() , 编译器也晓得 x * y 的类型,但你就是没办法得到那样的信息(指返回类型)。 C++0x 中的关键词 decltype 扫除了这个盲点, 让你能够说 “ multiply() 返回 x * y 类型的 东西 ” 。( decltype 是 "declared type" 的缩写,我把它读作谐音 “speckle type” 。)

 

decltype :模式

下面是一个完全泛化的封装 +() 操作符的函数因子。 这个 “ 加法 ” 因子不是一个模板,但它有一个模板函数, 这个模板函数带两个任意类型(当然是不同类型的)参数,并把它们相加,然后返回任意类型(可能跟两个参数的类型完全不同)的结 果。

 

C:/Temp>type plus.cpp

#include <algorithm>

#include <iostream>

#include <iterator>

#include <ostream>

#include <string>

#include <utility>

#include <vector>

using namespace std;

 

struct Plus {

    template <typename T, typename U>

    auto operator()(T&& t, U&& u) const

    -> decltype(forward<T>(t) + forward<U>(u)) {

        return forward<T>(t) + forward<U>(u);

    }

};

 

int main() {

    vector<int> i;

    i.push_back(1);

    i.push_back(2);

    i.push_back(3);

 

    vector<int> j;

    j.push_back(40);

    j.push_back(50);

    j.push_back(60);

 

    vector<int> k;

 

    vector<string> s;

    s.push_back("cut");

    s.push_back("flu");

    s.push_back("kit");

 

    vector<string> t;

    t.push_back("e");

    t.push_back("ffy");

    t.push_back("tens");

 

    vector<string> u;

 

    transform(i.begin(), i.end(), j.begin(), back_inserter(k), Plus());

    transform(s.begin(), s.end(), t.begin(), back_inserter(u), Plus());

 

    for_each(k.begin(), k.end(), [](int n) { cout << n << " "; });

    cout << endl;

 

    for_each(u.begin(), u.end(), [](const string& r) { cout << r << " "; });

    cout << endl;

}

 

C:/Temp>cl /EHsc /nologo /W4 plus.cpp

plus.cpp

 

C:/Temp>plus

41 52 63

cute fluffy kittens

 

拿 C++98/03 <functional> 中的 std::plus<T> ( 在 C++0x 没有 变动 ) 来作 对 比,后者是一个 类 模板,你不得不 传递 模板参数 类型来 调 用 plus<int>() 和 plus<string>() ,重 复 声明一次元素 类型。并且后者那个形式 为 T operator()(const T& x, const T& y) 的非模板函数 调 用操作符,如果不借助于 隐 式 类型 转换 ,就不能将两 种 不同 类型的 东 西相加,更不用 说 3 种 不同 类型的情况了( 译 注:两个参数 类型 + 一个返回 类型)。(你可以 传递 string 和 const char * 类型的 实 参来 调 用 const plus<string>() ,那 样 的 话 就会在串接操作之前,基于第二个参数 (const char * ) 构建一个 临时 string , 这样 做在性能上不可取)。 再者,因 为 它的参数是 const T& 形式的, 这 就不能使用 C++0x 的 move 语 意来 获 得好 处 。 Plus 避免了上述 问题 : 调 用 Plus() 不需要重 复 声明元素的 类型,它也可以 处 理 “3 种 ” 不同 类型的情况,并且它用了完美 转发 ,因而能 够 使用 move 语 意。

 

trailing return type

 

现 在 让 我 们 再来看看 这 个模板函数 调 用操作符:

 

template <typename T, typename U>

auto operator()(T&& t, U&& u) const

-> decltype(forward<T>(t) + forward<U>(u)) {

    return forward<T>(t) + forward<U>(u);

}

这 里的 auto 与 for ( auto i = v.begin(); i != v.end(); ++i) 中的含 义 完全不同 , 在 for 中它是指 “ 把用来初始化 对 象的 类型当做 对 象的 类型 ” ,而在 这 里它是指 “ 这 个函数有 trailing-return-type ,只有指定 实 参之后,才能确定它返回什 么类型 ”(C++0x 提案 N2857 中把 这 个称作 “late-specified return type ” ,但它将被重命名 为 “trailing-retrun-type ” (提案 N2859 ) ) 。 这 里看起来和 lambda 函数是如何指定返回 类型的很相似,其 实 它 们 就是一 样 的。 lambda 函数的返回 类型必 须 出 现 在 lambda 导 引符 [] 之后(右 边 )。在 这 里, decltype-powered 类型也必 须 出 现 在函数参数 和 之后(右 边 )。 autoT 和 对 它是可 见 的,但是函数参数 和 还 不可 见 , 这 就是 为 什 么 需要 decltype 的原因。(从技 术 上来 讲 , decltype(forward<T>(*static_cast<T *>(0)) + forward<U>(*static_cast<U *>(0)) ) 可以在左 边 出 现 ,但那看起来会 让 人不舒服)。

 

至于在返回 语 句中 还 要使用与 传给 decltype 的表达式相同的形式,是 为 了确保在任何情况下都能正确工作。(突 击测验 : 为 什 么 decltype(t + u) 就不 对 呢?)。 这 里的重 复 是不可避免的,但因 为 集中 - 只出 现 一次且代 码 位置靠近,所以不会有什 么 危 险 。

 

另一个例子

考 虑 到例子的完整性,下面是一个 “3 种 ” 不同 类型的示例:  

 

C:/Temp>type mult.cpp

#include <algorithm>

#include <iostream>

#include <iterator>

#include <ostream>

#include <utility>

#include <vector>

using namespace std;

 

struct Multiplies {

    template <typename T, typename U>

    auto operator()(T&& t, U&& u) const

    -> decltype(forward<T>(t) * forward<U>(u)) {

        return forward<T>(t) * forward<U>(u);

    }

};

 

class Watts {

public:

    explicit Watts(const int n) : m_n(n) { }

    int get() const { return m_n; }

private:

    int m_n;

};

 

class Seconds {

public:

    explicit Seconds(const int n) : m_n(n) { }

    int get() const { return m_n; }

private:

    int m_n;

};

 

class Joules {

public:

    explicit Joules(const int n) : m_n(n) { }

    int get() const { return m_n; }

private:

    int m_n;

};

 

Joules operator*(const Watts& w, const Seconds& s) {

    return Joules(w.get() * s.get());

}

 

int main() {

    vector<Watts> w;

    w.push_back(Watts(2));

    w.push_back(Watts(3));

    w.push_back(Watts(4));

 

    vector<Seconds> s;

    s.push_back(Seconds(5));

    s.push_back(Seconds(6));

    s.push_back(Seconds(7));

 

    vector<Joules> j;

 

    transform(w.begin(), w.end(), s.begin(), back_inserter(j), Multiplies());

 

    for_each(j.begin(), j.end(), [](const Joules& r) { cout << r.get() << endl; });

}

 

C:/Temp>cl /EHsc /nologo /W4 mult.cpp

mult.cpp

 

C:/Temp>mult

10

18

28

 

你可能会 问 “ 所有的 这 些 处 理真的有必要 么 ” ,答案是 Yes ,有必要。我已 经 介 绍 了完美 转发 和 decltype 是如何 让 算 术 运算函数因子使用起来更容易(不用重 复 声明元素 类型),更灵活(可以混合使用不同的参数和返回 类型),更有效率(使用 move 语 意)。最重要的是,完美 转发 和 decltype 让 你能 够编 写更 简洁 明了的代 码 ,而不灵活和低效的代 码 不是 简洁 明了的 - 这 点是我 们 无法忽 视 的。

 

级规则

decltype 是有一些规则来驱动的。然而,如果你遵照上面的模式就没关系,能正常工作。我很少那样说 C++ ,但是在这里是这样 的。

虽然大多数 decltype 应 用遵循上面介 绍 的模式,但 decltype 还 可以用于其他 环 境。在那些情况下,你就用到了 decltype 的高级模式,你应该 全面地阅读那些规则 ,它们在 C++0x 提案 N2857   7.1.6 .2 [dcl.type.simple]/4 中被给出。

 

等等,有一些要

decltype 是第五个且是最后一个添加到 VC10 中的 C++0x 核心语言特性。 虽然 VC10 CTP 中还没有,但 VC10 Bata 1 中会有。而且 VC10 Beta 1 中还有很多 C++0x 标准库特性,我会在后续文章中介绍它们 。

Stephan T. Lavavej

Visual C++ Libraries Developer

Published Wednesday, April 22, 2009 10:06 AM by vcblog

翻 译 : 飘飘白云

 

( 转载时请 注明作者和出 处 。未 经许 可, 请 勿用于商 业 用途 )

<全文完>

 


posted @ 2009-06-05 16:59  飘飘白云  阅读(326)  评论(0编辑  收藏  举报
本博客遵循 Creative Commons License “署名-非商业用途-保持一致”创作共用协议。 与我联系