复制初始化 - 从 'int' 到非标量类型的转换

copy initialization - conversion from 'int' to non-scalar type

我想知道我应该如何定义 class my_int 以便 从 int 到 std::complex< my_int > 的转换由编译器而不是我手动。

如果 4 没有被强制转换为“my_int

,则以下程序不会编译
// Example program
#include <iostream>
#include <string>
#include <complex>

struct my_int
{
    my_int() : _i(0) {}
    my_int(const my_int& mi) : _i(mi._i) {}

    my_int(int i) : _i(i) {}
    operator int(){return _i;}

    int _i;
};

std::ostream& operator<<(std::ostream& os, const my_int& mi)
{
    os << mi._i;
    return os;
}

int main()
{
  std::complex<my_int> ci = 4; // Casting 4 to my_int works

  std::cout << ci;
}

我知道如果你用 std::complex<my_int> ci(4) 初始化 ci 它可以工作,但我希望它与复制初始化一起工作。

您可以定义复杂的 class 并以这种方式编写构造函数。

  Complex(int re, int im = 0);

在这种情况下,编译器会在

上将 int 隐式转换为复数
Complex c = 5;

貌似问题是,可以用直接初始化上下文解决,例如

std::complex<my_int> ci{4}; 

但是,还有一个隐藏的问题:the effect of instantiating the template complex for any type other than float, double or long double is unspecified,所以你必须明确地专门化它,正如StoryTeller在评论中指出的那样。