How to conditionally add a function to a class template?

前端 未结 5 2046
你的背包
你的背包 2020-12-29 10:45

I have a Matrix class template as follows:

template
class Matrix
{
    T data[nrows][ncols];
public:
         


        
5条回答
  •  不思量自难忘°
    2020-12-29 11:50

    You can do it with std::enable_if in the following mode

    template 
    typename std::enable_if::type setIdentity ()
     { /* do something */ }
    

    A full example

    #include 
    
    
    template
    class Matrix
    {
        T data[nrows][ncols];
    
    public:
        T& operator ()(std::size_t i, std::size_t j)
        { return data[i][j]; }
    
        template 
        typename std::enable_if::type setIdentity ()
         { /* do something */ }
    };
    
    int main()
     {
       Matrix  mi3;
       Matrix  mnoi;
    
       mi3.setIdentity();
       // mnoi.setIdentity(); error
    
      return 0;
    }
    

    --- EDIT ---

    As pointed in a comment by Niall (regarding the TemplateRex's answer, but my solution suffer from the same defect) this solution can be circonvented expliciting the number of rows and columns in this way

    mi3.setIdentity<4, 4>();
    

    (but this isn't a real problem (IMHO) because mi3 is a square matrix and setIdentity() could work with real dimensions (nrows and ncols)) or even with

    mnoi.setIdentity<4, 4>()
    

    (and this is a big problem (IMHO) because mnoi isn't a square matrix).

    Obviously there is the solution proposed by Niall (add a static_assert; something like

        template 
        typename std::enable_if::type setIdentity ()
         {
           static_assert(r == nrows && c == ncols, "no square matrix");
    
           /* do something else */ 
         }
    

    or something similar) but I propose to add the same check in std::enable_if.

    I mean

    template 
    typename std::enable_if<    (r == c)
                             && (r == nrows)
                             && (c == ncols)>::type setIdentity ()
     { /* do something */ }
    

提交回复
热议问题