Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion with operator

This is in part inspired by this question. When I write the code:

void test(std::string inp)
{
  std::cout << inp << std::endl;
}

int main(void)
{
  test("test");
  return 0;
}

"test" is implicitly converted from const char* to std::string, and I get the expected output. However, when I try this:

std::string operator*(int lhs, std::string rhs)
{
  std::string result = "";

  for(int i = 0; i < lhs; i++)
  {
    result += rhs;
  }

  return result;
}

int main(void)
{
  std::string test = 5 * "a";
  return 0;
}

I get the compiler error, invalid operands of types 'int' and 'const char [2]' to binary 'operator*'. "a" was not implicitly converted to std::string here, instead it remained a const char*. Why is the compiler able to determine the need for an implicit conversion in the case of a function call, but not for the case of an operator?

like image 520
R_Kapp Avatar asked Nov 06 '15 18:11

R_Kapp


People also ask

What is an implicit operator?

According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting.

What is a conversion operator?

A conversion operator, in C#, is an operator that is used to declare a conversion on a user-defined type so that an object of that type can be converted to or from another user-defined type or basic type. The two different types of user-defined conversions include implicit and explicit conversions.

What is implicit conversion give an example?

Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.


1 Answers

Indeed, operators have different rules from other kinds of functions.

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.

([over.match.oper]/1)

like image 135
Brian Bi Avatar answered Oct 06 '22 01:10

Brian Bi