How to conditionally add a function to a class template?

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

    The lazy and needlessly repetitive way

    Just add a partial specialization:

    template
    class Matrix
    {
        T data[N][N];
    public:
        T& operator ()(std::size_t i, std::size_t j)
        {
            return data[i][j];
        }
    
        void setidentity(/*whatever params*/) { std::cout << "yay!"; }
    };
    

    Live Example

    For general N * M matrices, the general template will be instantiated, whereas only for N * N matrics, this specialization is a better match.

    Disadvantage: code repetition of all regular code. Could use a base class, but it's actually easier to do some SFINAE magic (below)

    A slightly harder but more economical way

    You can also use SFINAE by adding hidden template parameters N and M that default to nrows and ncols to setidentity, and to enable_if on the condition N == M.

    template
    class Matrix
    {
        T data[nrows][ncols];
    public:
        T& operator ()(std::size_t i, std::size_t j)
        {
            return data[i][j];
        }
    
        template * = nullptr>
        void setidentity(/*whatever params*/) { 
            static_assert(N == nrows && M == ncols, "invalid");
            std::cout << "yay!"; 
        }
    };
    

    Or, since the question was tagged C++11, use typename std::enable_if<(N == M)>::type instead.

    Live Example

提交回复
热议问题