简体   繁体   English

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

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

Let's say we have a class 假设我们有一堂课

class X {
public:
  void my_method() { std::cout << "I'm X"; }
} 

and we have a template class: 我们有一个模板类:

template<typename T> 
class Y
{
public:
    void put(typename T item) { item.my_method(); }

};

I want to execute item.my_method(); 我想执行item.my_method(); if the class Y is instantiated with a X class (if not there would be a compile error). 如果类Y用X类实例化(如果没有,则会出现编译错误)。 How can I work this out? 我该如何解决这个问题?

Not sure I fully understand the question because what you have works. 我不确定我完全理解这个问题,因为你有什么作品。

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

When Y is used with a class that does not have the my_method() member, it fails to compile. 当Y与没有my_method()成员的类一起使用时,它无法编译。

What you want is template specialization : 你想要的是模板专业化

template<>
class Y <X>
{
public:
    void put(X item) { item.my_method(); }
};

I believe you won't get a compiler error if you instantiate Y with a class other than X as long as you don't call put (something unique to templates). 我相信只要不调用put (模板特有的东西),如果用X以外的类实例化Y ,就不会出现编译错误。

You could use template specialization if put needs to do different things for different types. 如果你可以用模板特put需要为不同类型做不同的事情。

Simply un-templatize the put method and create it for type X alone. 只需取消模板化put方法并仅为X类创建它。 And put a check inside the method if T is 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
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM