V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
zhiqiang
V2EX  ›  C

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

  •  
  •   zhiqiang · Aug 13, 2018 · 3598 views
    This topic created in 2814 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
        1
    GeruzoniAnsasu  
       Aug 13, 2018
    没太懂,感觉你这个需求十分奇怪

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

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

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

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