如何用具有特定方法的类实例化C++模板
How can I instantiate a C++ template with a class with specific methods
假设我们有一个类
class X {
public:
void my_method() { std::cout << "I'm X"; }
}
我们有一个模板类:
template<typename T>
class Y
{
public:
void put(typename T item) { item.my_method(); }
};
如果类Y是用X类实例化的(否则会出现编译错误),我想执行item.my_method();
。我该怎么办?
我不确定我是否完全理解这个问题,因为你的方法有效。
class X
{
public:
void my_method() { std::cout << "I'm X"; }
};
class Z
{
};
template <typename T>
class Y
{
public:
void put(T item) { item.my_method(); }
};
int main(int argc, char* argv[])
{
// This compiles fine
X theX;
Y<X> theXY;
theXY.put( theX );
// ERROR: This fails to compile
Z theZ;
Y<Z> theYZ;
theYZ.put( theZ );
}
当Y与没有my_method()
成员的类一起使用时,它将无法编译。
您想要的是模板专业化:
template<>
class Y <X>
{
public:
void put(X item) { item.my_method(); }
};
我相信,如果用X
以外的类实例化Y
,只要不调用put
(模板特有的东西),就不会出现编译器错误。
如果put
需要为不同的类型做不同的事情,那么可以使用模板专门化。
只需取消put
方法的模板化,并单独为类型X
创建它。如果T
是X
,则在方法内部进行检查。
template<typename T> struct IsX; // unimplemented for rest of types
template<> struct IsX<X> { typedef X yes; }; // implemented for 'X' alone
template<typename T>
class Y
{
public:
void put (X item) { typedef typename IsX<T>::yes check; item.my_method(); }
//^^^^^^^^^^^^^^^ compile time ensure that it's for 'X only
};
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 检查某些类型是否是模板类 std::optional 的实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 模板化类构造函数的模板实例化
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 受约束的成员函数和显式模板实例化
- 对显式实例化的模板函数的未定义引用
- [temp.variadic]中关于包扩展实例化的措辞