How to conditionally add a function to a class template?

前端 未结 5 2045
你的背包
你的背包 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:34

    A basic, but simple solution not mentioned by any other answer: you can use std::conditional and inheritance.
    It follows a minimal, working example:

    #include
    #include
    
    struct HasSetIdentity {
        void setIdentity() { }
    };
    
    struct HasNotSetIdentity {};
    
    template
    class Matrix: public std::conditional<(nrows==ncols), HasSetIdentity, HasNotSetIdentity>::type
    {
        T data[nrows][ncols];
    public:
        T& operator ()(std::size_t i, std::size_t j)
        {
            return data[i][j];
        }
    };
    
    int main() {
        Matrix m1;
        m1.setIdentity();
        Matrix m2;
        // Method not available
        // m2.setIdentity();
    }
    

    You can still move data down the hierarchy if you need them to be shared by all the subobjects.
    It mostly depends on the real problem.

提交回复
热议问题