C++ why does SFINAE fail with only a class template parameter?

前端 未结 3 1295
鱼传尺愫
鱼传尺愫 2021-01-18 03:14

I\'m using SFINAE in the style of this answer in order to call a generic vector object by using an appropriate member function. For example, the following code calls o

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 04:10

    In your failing example, the template parameter VectorType has already been determined by the time get is being resolved. To make SFINAE work, you need to make the template parameters you are using for SFINAE resolve at that method call. The following is a modification of your first example to work like you want to:

    template struct rank : rank { static_assert(I > 0, ""); };
    template<> struct rank<0> {};
    
    template
    struct VectorWrapper
    {
        auto get(int i) const
        {
            return get(v, i, rank<5>());
        }
    
        template::value> >
        auto get(int i, rank<2>) const
        {
            return v[i];
        }
    
        template::value> >
        auto get(int i, rank<1>) const
        {
            return v(i);
        }
    
        VectorType v;
    };
    

    This way, V is resolved when get is called, and it will correctly use SFINAE.

提交回复
热议问题