[英]How can I instantiate a C++ template with a class with specific methods
假設我們有一堂課
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(); }
};
我想執行item.my_method();
如果類Y用X類實例化(如果沒有,則會出現編譯錯誤)。 我該如何解決這個問題?
我不確定我完全理解這個問題,因為你有什么作品。
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(); }
};
我相信只要不調用put
(模板特有的東西),如果用X
以外的類實例化Y
,就不會出現編譯錯誤。
如果你可以用模板特put
需要為不同類型做不同的事情。
只需取消模板化put
方法並僅為X
類創建它。 如果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's for 'X only
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.