我可以防止将参数隐式转换为赋值运算符

Hen*_*und 3 c++ templates implicit-conversion

我正在实现一个类型(TParameter),该类型必须是布尔值(以指示该值是否有效)和任意类型的数据值。

想法是,如果方法采用某种类型的参数,则可以将其设置为false,以指示该值无效。

像这样:

someVariable = 123;   // use the value 123
someVariable = false; // mark variable as invalid/to-be-ignored
Run Code Online (Sandbox Code Playgroud)

我的代码的简化版本:

template <class T>

class TParameter
{
  public:
    TParameter()
    : m_value(),
      m_valid(false)
    {}

    // assignment operators
    TParameter& operator= (const T& value)
    {
      m_value = value;
      m_valid = true;
      return *this;
    }

    TParameter& operator= (bool valid)
    {
      m_valid = valid;
      return *this;
    }

  private:
    T m_value;
    bool m_valid;
};

  void test()
  {
    TParameter<int16_t> param;

    param = false;
    param = int16_t(123);
    param = 123;
  }
Run Code Online (Sandbox Code Playgroud)

编译代码时出现错误:

ambiguous overload for ‘operator=’ (operand types are ‘TParameter<short int>’ and ‘int’)
Run Code Online (Sandbox Code Playgroud)

问题在于整数值可以隐式转换为a bool,因此其中的最后一行test()不会编译。

是否可以告诉编译器TParameter& operator= (bool valid)仅在参数为时才使用bool(即禁用隐式强制转换为bool)?

son*_*yao 5

您可以制作第一个重载模板,然后仅当传递第二个重载时bool才是首选(因为在相同情况下,非模板功能优于模板)。否则,将选择模板版本,因为它是完全匹配的。

template <typename X>
TParameter& operator= (const X& value)
{
  m_value = value;
  m_valid = true;
  return *this;
}

TParameter& operator= (bool valid)
{
  m_valid = valid;
  return *this;
}
Run Code Online (Sandbox Code Playgroud)

生活

顺便说一句:在您的代码中,隐式转换在operator=被调用时发生。int转换为int16_t,然后传递给operator=。在上面的代码中,隐式转换发生在operator=,即内m_value = value;