C++ 如何实例化C++;具有特定方法的类的模板

C++ 如何实例化C++;具有特定方法的类的模板,c++,templates,inheritance,C++,Templates,Inheritance,假设我们有一节课 class X { public: void my_method() { std::cout << "I'm X"; } } X类{ 公众: void my_method(){std::cout您需要的是: 模板 Y类 { 公众: void put(X项){item.my_method();} }; 我相信,如果使用X以外的类实例化Y,只要不调用put(模板特有的东西),就不会出现编译器错误 如果put需要为不同的类型执行不同的操作,则可以使用模板专门化。我

假设我们有一节课

class X {
public:
  void my_method() { std::cout << "I'm X"; }
} 
X类{
公众:
void my_method(){std::cout您需要的是:

模板
Y类
{
公众:
void put(X项){item.my_method();}
};

我相信,如果使用
X
以外的类实例化
Y
,只要不调用
put
(模板特有的东西),就不会出现编译器错误


如果
put
需要为不同的类型执行不同的操作,则可以使用模板专门化。

我不确定是否完全理解这个问题,因为您所做的工作是有效的

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 );
}
X类
{
公众:

void my_method()

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
};
template struct IsX;//其余类型未实现
模板结构IsX{typedef X yes;};//仅为“X”实现
模板
Y类
{
公众:
void put(X项){typedef typename IsX::yes check;item.my_method();}
//^^^^^^^^^^^^^^^编译时确保它仅用于'X'
};

我认为OP希望这样,即使
Z::my_method()
存在,但编译器仍应报告错误。
put
方法应仅对类型
X
@iammilind有效-我将尝试从提问者那里获得澄清。你是对的。这是我的愚蠢。代码不起作用,因为我分裂成了.cpp和.hpp文件。在将整个代码放入标题后,它正常工作。谢谢。如果
类Y
很大,那么OP必须重写所有在实际
类Y
@iammilind中没有改变的东西:我会在类Y上使用(模板化)继承来解决它。请注意OP的问题非常笼统,因此,没有办法提供“完美答案”看我的答案,我认为这会使解决方案变小。@iammilind:你在猜测OP的意思。如果提供的答案不令人满意,我宁愿让OP添加细节。这难道不会使整个模板机制变得多余吗?如果你强迫编译器在不满意时给出错误任何不是Y的东西,为什么要使用带有Y的模板?@trutheality,
Y
可以用于除
put()
以外的其他方法。仅用于
put()
我们进行专门化。鉴于到目前为止的答案,对于您真正要求的内容,似乎存在一些困惑。您能澄清这个问题吗?
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 );
}
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
};