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

How can I instantiate a C++ template with a class with specific methods

本文关键字:实例化 C++ 模板 方法 何用具      更新时间:2023-10-16

假设我们有一个类

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创建它。如果TX,则在方法内部进行检查。

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
};