How to resolve ambiguity in overloaded functions using SFINAE

后端 未结 4 1627
太阳男子
太阳男子 2021-02-08 22:21

I have an incredibly exciting library that can translate points: it should work with any point types

template
auto translate_point(T &p, int x         


        
4条回答
  •  后悔当初
    2021-02-08 23:06

    With SFINAE, I would do something like this:

    template
    auto translate_point(T &p, int x, int y) -> decltype(p[0], void())
    {
        p[0] += x;
        p[1] += y;
    }
    
    template::value>
    auto translate_point(T &p, int x, int y) -> decltype(p.x, p.y, void())
    {
        p.x += x;
        p.y += y;
    }
    

    By doing this, when T = (class with StupidPoint as base class), the second overload will be called.

    But it is easier with a simple overload, as pointed out by m.s.

提交回复
热议问题