c++ - 如何在 C++ 中为嵌套模板数字类型类编写构造函数?

标签 c++ templates constructor type-conversion

我正在实现一些我想“嵌套”数字类型的东西。我正在努力以右侧可以是数字文字的方式编写构造函数。这是我的问题的缩小版本:

template <typename Scalar>
class A
{
  public:
    A(Scalar a):v(a){};
    Scalar v;
};

template <typename Scalar>
class B
{
  public:
    B(Scalar a):v(a){};
    Scalar v;
};

int main()
{
  A<double> a = 1.0;
  B<double> b = 1.0;
  B<A<double>> ba = 1.0;
}

编译错误是

error: no viable conversion from 'double' to 'B<A<double>>'

不想B<A<double>> b = A<double>(1.0); .有没有办法改变我的 AB类,以便原始代码有效?

最佳答案

你想要的是转发构造函数。这是一个构造函数,它采用参数来构造包装对象,并使用提供的参数调用该对象的构造函数。看起来像

template <typename Scalar>
class A
{
public:
    A(Scalar a):v(a){};
    Scalar v;
};

template <typename Scalar>
class B
{
public:
    B(Scalar a): v(a) {}
    template <typename... Args, 
              std::enable_if_t<std::is_constructible_v<Scalar, Args...>, bool> = true>
    B(Args&&... args) : v(std::forward<Args>(args)...) {}
    Scalar v;
};

int main()
{
    A<double> a = 1.0;
    B<double> b = 1.0;
    B<A<double>> ba = 1.0;
}

std::enable_if_t<std::is_constructible_v<Scalar, Args...>, bool> = true模板的一部分利用了 SFINAE限制此构造函数仅在能够构造 Scalar 时才起作用.这是必需的,因为可变参数模板是贪婪的,几乎可以匹配任何东西,包括在提供类类型的非 const 左值时被认为是比复制构造函数更好的构造函数。

关于c++ - 如何在 C++ 中为嵌套模板数字类型类编写构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71727991/

相关文章:

c++ - 奇怪的 QT Unsigned Int 错误

c++ - 从 Class<U> 调用 Class<T> 的私有(private)构造函数

c++ - 避免基于构造函数值 C++ 创建对象

c++ - 面向对象 : how to create a function "addFruit" to add fruit into a vector<fruit>

c++ - 在同一架构上运行的静态编译的纯标准 C++ 程序是否可移植?

c++ - 通过 const 引用传递基本值真的会损害性能吗?

c++ - 我如何确定模板参数参数是否是模板内结构中另一个类的实例? C++

c++ - 构造函数中神秘的堆栈溢出

Java 构造函数列表作为字符串

c++ - 形状中的 OpenGL 着色