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

Let, say, 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();if class Y is instantiated by class X (if there were no compilation error). How can i fix this?

+3
source share
4 answers

Not sure if I fully understand the question because you have work.

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 a member my_method(), it does not compile.

+3
source

You want a specialization template :

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

I believe that you will not get a compiler error if you create an instance Ywith a class other than Xif you do not call put(something unique to the templates).

You can use specialized specialization if putyou need to do different things for different types.

+2
source

Just do not template the method putand create it only for the type X. And put a check inside the method if 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 for 'X only
};
+1
source

All Articles