我有這個模板化的基類:
template <class V>
class ValueParam
{
public:
virtual V convert(const char* f) const = 0;
protected:
V val;
};
請注意,我可以存盤一些val具有 type 的值V,并且我有一個convert函式,當我在ValueParam物件上呼叫它時,它會自動回傳正確的型別。
intas 型別的示例V:
class IntParam : public ValueParam<int>
{
public:
IntParam(int i) { val = i; }
int convert(const char* f) const override { return atoi(f); }
};
然后我們可以使用:
IntParam i(1234); // The value of val is 1234
int x = i.convert("1"); // x will be 1
現在我在char*用作我的型別時遇到了一個問題V:
class StrParam : public ValueParam<char*>
{
public:
StrParam(const char* str, size_t max_len)
{
val = new char[max_len 1]{};
strncpy(val, str, max_len 1);
}
~StrParam() { delete[] val; }
char* convert(const char* f) const override { return f; } // Doesn't compile: f is const char*
};
我不想做任何常量轉換。
幸運的是,我不需要convert以任何方式可變的結果。我可以將其回傳型別更改為可以編譯的型別嗎?
那會是什么型別?因為只是將其更改為virtual const V convert...將意味著回傳型別StrParam將變為char* const convert...并且顯然仍然不起作用。
uj5u.com熱心網友回復:
您可以const為回傳型別添加指向型別:
// for non-pointer type
template <typename T>
struct add_const_pointee { using type = T; };
// for pointer type
template <typename T>
struct add_const_pointee<T*> { using type = const T*; };
// helper type
template <typename T>
using add_const_pointee_t = typename add_const_pointee<T>::type;
template <class V>
class ValueParam
{
public:
virtual add_const_pointee_t<V> convert(const char* f) const = 0;
// ^^^^^^^^^^^^^^^^^^^^^^
protected:
V val;
};
和
class StrParam : public ValueParam<char*>
{
public:
StrParam(const char* str, size_t max_len)
{
val = new char[max_len 1]{};
strncpy(val, str, max_len 1);
}
~StrParam() { delete[] val; }
const char* convert(const char* f) const override { return f; }
// ^^^^^
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380293.html
上一篇:可以根據運行時的結果實體化函式模板ifelse條件而無需在C 中創建類模板嗎?
下一篇:專業化不包含在主模板中宣告的資料
