专用版本是否可以与原始模板 class 共享某些功能?
Is it possible for a specialized version to share some functionalities with the original template class?
class 的特殊版本是否可以共享原始模板 class 的部分或全部功能?
即考虑有一个模板 class,
template <typename T>
class A
{
A()
{}
A(const A& ref)
{}
void f1()
{
//do something
}
void f2()
{
//do something
}
void f3()
{
//do something
}
}
并且它有一个针对特定数据类型的专用版本,它只打算在通用版本的基础上添加一些附加功能。
template<>
class A<int>
{
void f4()
{
//do something
}
}
现在我特别想要的是这个专用版本共享其通用版本的所有内容,如果可能的话包括构造函数。
通常可以通过重组 class 层次结构来实现:
template <typename T>
class A_base
{
// All the f1() functions, et. al, implemented here
};
template<typename T> class A : public A_base<T> {
public:
// An empty shell of a class, with the constructor
// forwarding its arguments to the superclass.
template<typename ...Args> A(Args && ...args)
: A_base(std::forward<Args>(args)...)
{
}
};
template<>
class A<int> : public A_base<int>
{
// Same constructor.
void f4()
{
//do something
}
};
您最终将所有 class 方法、class 成员移动到基础 class 中,而您的模板 class 仅包含从基础派生的内容class模板;否则是一个空立面。
然后,您的专业化以相同的方式从基础 class 派生,并添加自己的方法。
另一种方法是实现这种推导"backwards"。
// Empty template class.
template<typename T> class A_extra {};
// Your specialization, with the extra method:
template<>
class A_extra<int> {
void f4()
{
}
};
// And the template class inherits from it:
template<typename T> class A : public A_extra<T> {
// Your template class
};
根据模板的具体细节class,一种或另一种方法应该可行;或同一主题的一些变体。
class 的特殊版本是否可以共享原始模板 class 的部分或全部功能?
即考虑有一个模板 class,
template <typename T>
class A
{
A()
{}
A(const A& ref)
{}
void f1()
{
//do something
}
void f2()
{
//do something
}
void f3()
{
//do something
}
}
并且它有一个针对特定数据类型的专用版本,它只打算在通用版本的基础上添加一些附加功能。
template<>
class A<int>
{
void f4()
{
//do something
}
}
现在我特别想要的是这个专用版本共享其通用版本的所有内容,如果可能的话包括构造函数。
通常可以通过重组 class 层次结构来实现:
template <typename T>
class A_base
{
// All the f1() functions, et. al, implemented here
};
template<typename T> class A : public A_base<T> {
public:
// An empty shell of a class, with the constructor
// forwarding its arguments to the superclass.
template<typename ...Args> A(Args && ...args)
: A_base(std::forward<Args>(args)...)
{
}
};
template<>
class A<int> : public A_base<int>
{
// Same constructor.
void f4()
{
//do something
}
};
您最终将所有 class 方法、class 成员移动到基础 class 中,而您的模板 class 仅包含从基础派生的内容class模板;否则是一个空立面。
然后,您的专业化以相同的方式从基础 class 派生,并添加自己的方法。
另一种方法是实现这种推导"backwards"。
// Empty template class.
template<typename T> class A_extra {};
// Your specialization, with the extra method:
template<>
class A_extra<int> {
void f4()
{
}
};
// And the template class inherits from it:
template<typename T> class A : public A_extra<T> {
// Your template class
};
根据模板的具体细节class,一种或另一种方法应该可行;或同一主题的一些变体。