代码之家  ›  专栏  ›  技术社区  ›  yageek

json11库关于隐式构造函数的代码解释

  •  1
  • yageek  · 技术社区  · 7 年前

    我正在阅读 main json11 header file .

    template <class T, class = decltype(&T::to_json)>
    Json(const T & t) : Json(t.to_json()) {}
    

    我正试图找到一些关于此用法的文档 decltype class 在模板声明中,但没有成功。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Angew is no longer proud of SO    7 年前

    它正在使用 SFINAE (" S 替代 F 阿留尔 A. n rror”),这是一种用于高级模板的常用技术。在本例中,它被用作原始模板 (1) 测试类型是否 T 具有名为的函数 to_json

    T::to_json 格式良好(有一个名为 to_json T ), decltype(T::to_json) 表示有效类型,构造函数模板可以正常使用。

    然而,如果 T: :to_json 格式不正确(即,如果没有 内部成员 T ),这意味着将模板参数替换为

    因此,如果类型 T to_json ,可以使用类型为的对象 T Json 对象如果没有此类成员 T


    (1) 我是说 原油 Json 可以接受。更紧密的拟合测试可能如下所示:

    template <class T, class = std::enable_if_t<std::is_constructible<Json, decltype(std::declval<const T>().to_json())>::value>>
    Json(const T & t) : Json(t.to_json()) {}
    

    [Live example]