在初始化 class 类型时,C++ 可以进行多少次隐式转换以将一种用户定义类型转换为另一种用户定义类型?

How many implicit conversions can C++ do to convert one user-defined type to another when initializing class types?

#include <iostream>

struct Gadget
{
  Gadget() { puts("Gadget default"); }
  Gadget(char const *a) { puts("Gadget-const char* constructor"); }
  Gadget(Gadget const &other) { puts("Gadget copy"); }
  ~Gadget() { puts("\nGadget destruction"); }
};

struct Work
{
  Work() { puts("default"); }
  Work(const Gadget &a) { puts("Work-Gadget constructor"); }
  // Work(char const *a) { puts("Work-const char* constructor"); }
  Work(Work const &other) { puts("copy"); }
  ~Work() { puts("\nWork destruction"); }
};

int main()
{
  using namespace std;
  Work w = "std";  // error here;
}

但是

Work w("std"); // works fine
Work w = Gadget("std"); // works fine
Work w = Work("std"); // works fine

c++能做的隐式转换有没有限制? 如果是,那么在什么情况下会发生隐式转换?

只有一个user-defined conversion is allowed in implicit conversion sequence. (BTW standard conversions don't have such limits.) Work w = "std"; performs copy initialization,它需要两个用户自定义转换,一个从char const *Gadget,一个从GadgetWork

Work w("std");执行direct initialization,只需要一次用户自定义转换(从char const *Gadget),然后传递转换后的GadgetWork的构造函数直接构造w.

the implicit conversion in copy-initialization must produce T directly from the initializer, while, e.g. direct-initialization expects an implicit conversion from the initializer to an argument of T's constructor.

Work w = Work("std"); 中,一个临时的 Work 被显式构造为 Work("std")(其工作原理如上所述),然后 w 从临时的 Work.

Work w = Gadget("std");中,一个临时Gadget被显式构造为Gadget("std"),然后w从临时Gadget复制初始化;其中只需要一个用户定义的转换(从 GadgetWork)。