zhiqiang
V2EX  ›  C

C++ SNINAE 如何判断指定函数是否存在?

  •  
  •   zhiqiang · Aug 13, 2018 · 4090 views
    This topic created in 3004 days ago, the information mentioned may be changed or developed.

    我要对每个有std::string to_string(T)函数的类型 T,都自动定义std::cout << T(实现为std::cout << to_string(T))。

    BOOST_TTI_HAS_MEMBER_FUNCTION可以检查类是否有指定成员函数,但我没找到如何检查是否有普通函数。

    9 replies  •  2018-12-13 18:00:50 +08:00
    GeruzoniAnsasu
    GeruzoniAnsasu
    Aug 13, 2018
    1
    没太懂,感觉你这个需求十分奇怪

    对于每个不同的 T,必然要实现不同的 to_string(T) ,那实现的时候顺便定义 operator<<(std::cout,T) 不就好了?
    zhiqiang
    zhiqiang
    OP
    Aug 13, 2018
    2
    @GeruzoniAnsasu 有多个 T,单写一个还比较麻烦。

    另外我是对每个类 T,自动实现`vector<T>, map<T>, set<T>`等一大堆类型的`to_string`。那每个类型就要手工写四个`operator<<(std::cout,T_T)`。
    bilosikia
    bilosikia
    Aug 13, 2018
    3
    首先是 SFINAE, 不是 SNINAE
    其实你的需求是要实现重载<<操作符
    geelaw
    geelaw
    Aug 13, 2018❤️1
    4
    类似 enable_if_t 的用法,自己实现一个不就行了。

    https://gist.github.com/GeeLaw/a93e60f05c0257278f36b199d9987f53
    GeruzoniAnsasu
    GeruzoniAnsasu
    Aug 13, 2018❤️1
    5
    其实我感觉

    template <typename T, typename I = decltype(to_string(T()))>
    decltype(std::cout << 1) operator<<(decltype(std::cout << 1) cout, const T &t)
    {
    return cout << to_string(t);
    }

    就行?

    对于没有定义 to_string(T)的 T,decltype 会失败
    AngelCriss
    AngelCriss
    Aug 13, 2018 via Android
    6
    指定成员函数也是要给函数签名的啊,要不然给个函数名就行,那就是编译期反射了
    Bladeindark
    Bladeindark
    Aug 14, 2018
    7
    ……都知道 SNINAE 了,外网不是大把这种 blog 么?
    codehz
    codehz
    Aug 16, 2018
    8
    几天前还看到有这样的骚操作 https://zhuanlan.zhihu.com/p/41922937
    可以模拟 concept 的 requires
    429839446
    429839446
    Dec 13, 2018
    9
    nlohmann/json 的 readme
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2899 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 13:19 · PVG 21:19 · LAX 05:19 · JFK 08:19
    ♥ Do have faith in what you're doing.