V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
iambic
V2EX  ›  问与答

请问一个 decltype 的问题( C++11)

  •  
  •   iambic · 2015-10-08 20:12:11 +08:00 · 2138 次点击
    这是一个创建于 3138 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看了 wiki 上对 decltype 的解释,我的理解就是 decltype 作用就是对表达式的值进行类型推导

    然后这个链接( http://www.stroustrup.com/C++11FAQ.html#decltype )给的例子也非常清晰

    void f(const vector<int>& a, vector<float>& b)
    {
        typedef decltype(a[0]*b[0]) Tmp;
        for (int i=0; i<b.size(); ++i) {
            Tmp* p = new Tmp(a[i]*b[i]);
            // ...
        }
        // ...
    }
    

    但是下面这段代码还是不太能够理解

    class Json final {
    // Implicit constructor: anything with a to_json() function.
    template <class T, class = decltype(&T::to_json)>
    Json(const T & t) : Json(t.to_json()) {}
    ...
    

    代码里注释说,任何一个带有 to_json 成员函数的类的对象,都可以用来初始化这个 Json 类。

    template<class T, class = decltype(&T::to_json)>

    这个到底应该怎么理解呢?

    谢谢

    2 条回复    2015-10-08 20:22:46 +08:00
    htfy96
        1
    htfy96  
       2015-10-08 20:17:59 +08:00
    这是 SFINAE 。要想实例化这个构造函数,即实例化这个函数模板,必须要能推导出 template 列表中的所有 type 。

    如果一个类 T 并不具有 T::to_json ,那么推导会失败。然而由于匹配失败不是失败的原理,它会去寻找其它构造函数或放弃
    iambic
        2
    iambic  
    OP
       2015-10-08 20:22:46 +08:00
    @htfy96
    decltype((&T::to_json)推导失败,所以匹配不上。。原来如此,多谢!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2741 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:08 · PVG 19:08 · LAX 04:08 · JFK 07:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.