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();
if the c开发者_JS百科lass Y is instantiated with a X class (if not there would be a compile error). 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.
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).
You could use template specialization if put
needs to do different things for different types.
Simply un-templatize the put
method and create it for type X
alone. And put a check inside the method if T
is 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's for 'X only
};
精彩评论