如何防止C ++参数被隐式转换? [重复]

问题描述 投票:1回答:1

我有一个提供接口以使用操作符访问其数组的类[]。像这样:

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;
};

我不希望此类的接口被错误类型的参数滥用,例如double / float,因为此处的隐式强制转换会导致错误的结果。该类的用户必须自己指出正确的idx,而不是躺在static_cast<int>()上。如果我接受double / float作为idx,将来很难调试我们的程序!

有没有一种方法可以拒绝它们传递非整数参数?最好是拒绝正在编译的有害代码。

c++ operator-overloading parameter-passing implicit-conversion illegalargumentexception
1个回答
0
投票

有没有办法我可以拒绝它们传递非整数参数?

是,您可以将它们标记为delete(自C ++ 11起)。

删除功能的任何使用都格式不正确(程序将无法编译)。

例如

delete

然后传递一个非template <typename T> std::enable_if_t<!std::is_same_v<int, T>, const string&> operator[]( T idx ) const = delete; 参数,例如intfloat,将选择此模板版本,然后程序将无法编译。


-1
投票

C ++ 11提供了double。您的问题与=delete非常相似。检查出来以获取更多详细信息。希望对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.