2012-08-14 83 views
1

我嘗試使用下面的代碼,但不能讓它來完成。從模板類派生?

任何人都可以看到這個問題?

class IResourceJob 
{ 
public: 
    virtual ~IResourceJob() {} 

    virtual void execute() = 0; 
}; 

template<typename T> 
class ResourceJob : public IResourceJob 
{ 
public: 
    void execute() 
    { 
     static_assert(false, "Specialised ResourceJob<T> not defined!"); 
    } 
}; 

template<> 
class ResourceJob<int> 
{ 
public: 
    void execute() 
    { 
     // test. 
    } 
}; 

下使用提供了一個編譯錯誤:

IResourceJob* job = new ResourceJob<int>; 

謝謝!

+2

你明確的專業化'ResourceJob '沒有從'IResourceJob'繼承,還有,靜態轉換是錯誤的,你的意思是'static_assert'? – 2012-08-14 21:19:57

+0

謝謝,抱歉 - static_cast是一個錯字。 – James 2012-08-14 21:26:09

回答

2

編譯器給出了永遠無法被實例化任何模板錯誤。對於類模板的成員函數(我假設你的意思static_assert),這是事實,所以編譯器被設置於右側給你診斷。

您想使條件取決於T,並巧妙地使其在實例化時總是評估爲假。例如像

template<typename T> 
struct always_false : std::false_type {}; 

template<typename T> 
class ResourceJob : public IResourceJob 
{ 
public: 
    void execute() 
    { 
     static_assert(always_false<T>::value, 
     "Specialised ResourceJob<T> not defined!"); 
    } 
}; 

由於編譯器無法知道用戶是否會放的always_false專業化(你不會,當然),它不能再早期拒絕的模板。

我也懷疑你是否想將static_assert放入execute,因爲你的錯誤信息表明ResourceJob作爲一個整體需要專門化。因此,將static_assert以外的成員函數放入類體中。如果您希望用戶專門整個模板,但只有成員函數,用戶反而需要說

// either "inline" and in the header, or not "inline" and in the .cpp file, but then 
// put this into the header: template<> void ResourceJob<int>::execute(); 
template<> inline void ResourceJob<int>::execute() { 

} 

這將提供execute另一個定義將由模板中使用如果Tint

1
IResourceJob* job = new ResourceJob<int>; 

因爲該類ResourceJob<int>不從IResourceJob衍生失敗。

的代碼應該是

template<> 
class ResourceJob<int> : public IResourceJob 
{ 
    public: 
    void execute() 
    { 
     // test. 
    } 
}; 
+0

謝謝,這是它... – James 2012-08-14 21:30:54

1

您需要導出模板專業化以及,如:

template<> 
class ResourceJob<int> : public IResourceJob 
{ /* ... */ }; 
+0

謝謝,原來如此! – James 2012-08-14 21:30:36