我正在尝试一切,但没有成功,我无法让它工作:/
例如我有这些类:
class Thing
{
public:
Thing() = default;
int getId() { return m_id; }
private:
int m_id;
};
template<class ThingType>
class Base
{
public:
Base(const std::vector<ThingType>& things)
: m_things(things) {};
Base<ThingType> operator+(Base<ThingType>& rhs)
{
// if not duplicated by id add new things
}
protected:
std::vector<ThingType> m_things;
};
class FooThings : public Base<Thing>
{
public:
FooThings(const std::vector<Thing>& things)
: Base(things) {};
};
我想像
一样使用它FooThings foo1(...);
FooThings foo2(...);
FooThings foos = foo1 - foo2;
但它给我错误“'初始化':无法从'Base'转换为'FooThings'”。我知道我在构造我的运算符重载代码时做错了但是我不知道该怎么写或者怎么写它
答案 0 :(得分:0)
您可以使用CRTP:
template<class ThingType, class Derived>
class Base
{
public:
Base(const std::vector<ThingType>& things)
: m_things(things) {};
Derived operator+(const Base<ThingType, Derived>& rhs)
{
std::vector<ThingType> sum = m_things;
sum.insert(end(sum), begin(rhs.m_things), end(rhs.m_things));
return Derived(sum);
}
protected:
std::vector<ThingType> m_things;
};
我修改了您的基类,引入了另一个模板参数Derived
,我用它来实现operator+