[英]How to specialize a templated member-function into a templated class in C++?
[英]How to specialize a non-templated-member function of a template class for multiple types?
我正在咬指甲部分專門針對多種類型的成員函數所需的語法。 這是我有的:
#include <cstdint>
#include <string>
class Property
{
public:
virtual int read(uint8_t *) = 0;
};
template<typename T>
class PropertyValue
{
T value_;
public:
int read(uint8_t *);
};
// specialized for std::string
template<>
int PropertyValue<std::string>::read(uint8_t *buf) { /* put string-value to buf */}
現在我想專門針對不同的枚舉類型使用read-function。 我嘗試了一下enable_if
和is_same
的組合看起來有意義,然后把它放在模板聲明中(編譯器告訴我現在有2個模板參數,而1是預期的)。
把它放在類定義中也沒有用。 外面......好吧,這就是我現在所擁有的。
// specialize for some enums
template<typename T>
typename std::enable_if<std::is_same<T, enum Enum1>::value ||
std::is_same<T, enum Enum2>::value, int>::type
PropertyValue<T>::read(uint8_t *buf)
{
return encode_enum(buf, value_);
}
我的想法錯在哪里?
編輯:寫這樣編譯和工作:
template<>
int PropertyValue<Enum 1>::read(uint8_t *buf)
{
return encode_enum(buf, value_);
}
template<>
int PropertyValue<Enum 2>::read(uint8_t *buf)
{
return encode_enum(buf, value_);
}
PropertyValue::value
本身不是模板。 它不是模板類,它不是模板函數。 它是模板類的成員,與模板本身不同。
你必須專注於整個班級。
template<>
class PropertyValue<std::string>
{
std::string value_;
public:
int read(uint8_t *)
{
// Your specialization goes here.
}
};
即使read()
本身是一個模板,您仍然必須專門化它的類,然后才能專門化模板類的模板成員。
當然,如果你的模板類有許多其他成員和方法,那么每個成員和方法都需要在這里專門化,導致大量代碼重復。 此時,您將面臨重構重復代碼的幾個選項。 最好的方法取決於具體細節。
但這就是它的完成方式......
編輯:一種常見的方法是使用輔助模板類:
template<typename T> class PropertyValue; // Forward declaration
template<typename T> class do_read {
public:
static int do_it( PropertyValue<T> &me, uint8_t *p )
{
// your default implementation
}
};
template<> class do_read<std::string> {
public:
static int do_it( PropertyValue<std::string> &me, uint8_t *p )
{
// your specialization
}
};
template<typename T>
class PropertyValue
{
T value_;
public:
int read(uint8_t *p)
{
return do_read<T>::do_it(*this, p);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.