2

I have a class that offers a interface to access it's array with a operator[]. Like this:

class MyArray {
public:
    MyArray( int iSize ) :
        m_iSize( iSize ),
        m_upArray( std::make_unique<string[]>( iSize ) ) {};

    const string& operator[]( int idx ) const {
        return std::max( 0, std::min( m_iSize - 1, idx ) );
    };

private:
    int m_iSize;

    std::unique_ptr<string[]> m_upArray;
};

I want not the interface of this class be abused with arguments of wrong type, such as double/float, because that the implicit casting here would lead to wrong result. The user of the class MUST finger out correct idx by themselves, instead of lying on a static_cast<int>(). If I accept a double/float as an idx, it is very hard to debug our programs in the future!

Is there a way I can reject them passing a non-int argument? It is best, to reject the diseased codes being compiled.

Leon
  • 1,489
  • 1
  • 12
  • 31

0 Answers0