[英]Specializing a template class member function for only one type
我有一個模板類,它有很多功能,但本質上是一個矢量類。 我想為bool類型添加一個函數。
#include <vector>
template <typename T>
class reflected{
private:
T*dev_;
T*host_;
ar_size size;
reflected<T>& operator=(reflected<T>& rhs);//do not impliment. assign not allowed.
reflected( reflected<T>& old); //do not impliment. Copy not allowed.
public:
reflected():size(0L),dev_(NULL),host_(NULL){}
reflected(ar_size n):size(n),dev_(NULL),host_(NULL){init();}
reflected(const T*x,ar_size n):size(n),dev_(NULL),host_(NULL){init();set(x);}
~reflected();
void init();
void init(ar_size n);
void init(const T*x,ar_size n);
void set(const T * x);
void setat(ar_index i, T x);
const T getat(ar_size i);
const T * devPtr();
const T operator [](const ar_index i);
ar_size length(){return size;}
};
我想在反射類的特殊情況下添加一個函數vector<ar_index> reflected<bool>::which()
,這是唯一有意義的情況。 做這個的最好方式是什么。 編譯器似乎不喜歡添加which()來反映並僅為bool定義它。
您可以在類模板中定義它
template <typename T> struct id { typedef T type; };
template <typename T>
class reflected{
private:
/* ... */
vector<ar_index> which(id<bool>) {
/* ... */
}
public:
/* ... */
vector<ar_index> which() { return which(id<T>()); }
};
如果您在reflected<T>
上調用which
T
您沒有給出正確的定義,則會產生編譯時錯誤。
如果您只想添加一個問題,可以將繼承與專業化結合起來:
template <typename T>
class reflected_base {
// your current 'reflected' contents go here
};
template <typename T>
class reflected : public reflected_base { };
template <>
class reflected<bool> : public reflected_base {
vector<ar_index> which();
};
這種方法的缺點是你必須為每個專業化重新實現某些操作(析構函數,復制構造函數等)。 另一種選擇是:
template <typename T>
class specialized_reflected { };
template <>
class specialized_reflected<bool> {
public:
vector<ar_index> which();
};
template <typename T>
class reflected : public specialized_reflected<T> {
// your current 'reflected' contents go here
};
但是,依賴名稱查找存在潛在問題。 第三個選項(可能是我選擇的選項)是使用非成員函數:
vector<ar_index> which(reflected<bool>&);
不能以你想要的方式直接完成。 但是你可以通過不為任何類定義reflected()
來實現類似的結果,除了專門的類。 如果您嘗試在不受支持的類上使用它,則會出現線性錯誤。
#include <string>
#include <sstream>
using namespace std;
template<typename A>
class Gizmo
{
public:
Gizmo(){};
int which();
};
template<> int Gizmo<bool>::which()
{
return 42;
}
int main()
{
Gizmo<bool> gb;
gb.which();
Gizmo<int> gi;
gi.which(); // LINKER ERROR for Gizmo<int>which()
return 0;
}
您可以將vector<ar_index> reflected<bool>::which()
到reflected<bool>
(僅限於它,而不是通用模板)。 如果您收到錯誤,也許您沒有正確地進行模板專業化...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.