So I have this code:
struct Foo {
Foo() { cout << "default\n"; }
Foo(const long long) { cout << "implicit\n"; }
};
struct Bar {
Bar(const short param) : param(param) {}
operator long long() const { return static_cast<long long>(param); }
const short param;
};
I would have thought that Foo foo = Bar(13) would have used my implicit cast and then the converting constructor. But it errors:
error: conversion from
Barto non-scalar typeFoorequested
This works fine though: Foo foo(Bar(13)). Why is my implicit cast used for explicit converting construction, but not for implicit converting construction?
The rules I got from https://en.cppreference.com/w/cpp/language/copy_initialization say:
The result of the conversion, which is a prvalue expression if a converting constructor was used, is then used to direct-initialize the object
Firstly the implicit conversion from
Bartolong long, and the one fromlong longtoFooare both user-defined conversion.Foo foo = Bar(13);perform copy initialization, the compiler will try to convertBartoFooimplicitly. Two implicit conversions are required, i.e. convertingBartolong longand then convertinglong longtoFoo. But only one user-defined conversion is allowed in one implicit conversion sequence.Foo foo(Bar(13));performs direct initialization. The constructors ofFoowould be examined and the best match is selected by overload resolution. Only one implicit user-defined conversion (fromBartolong long) is required; after thatFoo::Foo(long long)is called to constructfoodirectly.