假设我们有一个类
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()
成员的类一起使用时,它无法编译。
关于c++ - 如何使用具有特定方法的类实例化 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6379992/