gpt4 book ai didi

以派生类为参数的 C++ 基类构造函数(?)

转载 作者:行者123 更新时间:2023-12-03 06:53:52 25 4
gpt4 key购买 nike

用例:

  • Vector 类(实现一些数学)和派生的 Vector2D
  • 理想情况下,两个类都应该允许彼此“复制构造”

vector

namespace mu {
template<std::size_t N, typename T>
class Vector {
public:
// ...

template <typename... TArgs>
Vector(TArgs... args) : data({args...}) {}

Vector(const Vector &other) = default; // copy constructor

// ...
protected:
std::array<T, N> data;
};
}

Vector2D

namespace mu {
template<typename T>
class Vector2D : public Vector<2,T> {

public:

using Vector<2, T>::Vector; // inherit base class constructors

Vector2D(const Vector<2, T>& other) : Vector<2, T>(other) {}

// Vector2D specific functions, e.g. rotation
//...

};
}

注意:实际的类包含更多内容,但我将其浓缩为我认为此处最重要的代码。

问题是我无法实现一种可以从Vector2D构造Vector的方法,参见代码以下。所有其他情况都可以正常工作。

// Example 1 (compiles)
mu::Vector<2, int> a{1, 2};
mu::Vector<2, int> b{a};

// Example 2 (compiles)
mu::Vector2D<int> c{1, 2};
mu::Vector2D<int> d{c};

// Example 3 (compiles)
mu::Vector<2, int> e{1, 2};
mu::Vector2D<int> f{e};

// Example 4 (doesn't compile) <-- how to get this to work?
mu::Vector2D<int> g{1, 2};
mu::Vector<2, int> h{g};

当然,更普遍的问题是继承是否是构造这些类的正确方法。但我希望 Vector2D 具有 Vector 的所有功能以及 Vector 没有的附加功能。

最佳答案

你的 Vector类有两个构造函数:模板构造函数(用于值)和默认复制构造函数。

问题:复制构造函数是首选,但前提是存在完全匹配。

所以,初始化ba

mu::Vector<2, int> a{1, 2};
mu::Vector<2, int> b{a};

复制构造函数是首选,因为a是完全匹配

但是,正在初始化 hg

mu::Vector2D<int> g{1, 2};
mu::Vector<2, int> h{g};

g可以转换为 mu::Vector<2, int>不是完全匹配,因此首选模板构造函数,但模板构造函数不兼容。

一种可能的解决方案:SFINAE 在只有一个参数且参数派生自 mu::Vector 时禁用模板构造函数.

例如

template <typename... TArgs,
typename std::enable_if_t<sizeof...(TArgs) == N
or (not std::is_base_of_v<Vector, TArgs> && ...), int> = 0>
Vector(TArgs const & ... args) : data({args...}) {}

关于以派生类为参数的 C++ 基类构造函数(?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64634110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com