假设我们有两个班级
class A {
A Method();
}
class B {
B Method();
}
Method
函数做了一些重复的工作,例如,我们假设它只是返回类的副本。
如何使用模板在 1 中定义这 2 个函数?可以吗?
我尝试过做类似的事情
template <class C>
C C::Method() {
return *this;
}
Clang 给我错误:
Nested name specifier 'N::' for declaration does not refer into a class, class template or class template partial specialization
正如评论中指出的,这确实看起来像一个 XY 问题。
我想补充一点,您不需要创建副本的方法,因为复制构造函数和复制赋值运算符就是为此目的而存在的。
但是如果你真的想按照自己的方式来做,你可以使用 CRTP 解决你的问题:
template <typename Actual>
struct Impl
{
Actual copy()
{
return *static_cast<Actual*>(this);
}
};
struct A : public Impl<A>
{};
struct B : public Impl<B>
{};
您不能使用这样的语法定义多个不相关的函数,但您可以通过从模板类继承来向类添加成员。
template <class T>
class Cloneable
{
T Method() { return *static_cast<T*>(this); }
}
class A : public Cloneable<A> {}
class B : public Cloneable<B> {}
如果您有 C++23,您甚至可以使用显式对象参数删除强制转换
template <class T>
class Cloneable
{
T Method(this T& self) { return self; }
}
虽然不推荐,但您可以使用宏删除重复,如下所示:
#define CreateMethod(Type) Type Type::Method() { return *this;}
class A {
A Method();
};
class B {
B Method();
};
CreateMethod(A)
CreateMethod(B)