我的頭檔案定義了多個具有單個字符名稱的類;即 A 類、B 類、C 類等。每個類都支持 .getname(),它將類名作為字符回傳,給定一個隨機生成的字符,我面臨著使用模板使用 sizeof() 回傳大小的挑戰。
到目前為止,我無法弄清楚如何在給定 char 值的情況下定義型別別。
我希望允許以下內容列印 A 類的大小,為了簡化起見,我已將 testChar 分配給“A”,但實際上它可以是任何存在匹配類名的隨機字符;
class A
{
private:
char name;
public:
A(){name='A';}
char getName(){return name;}
};
template <typename X>
void printSize()
{
X newObject;
std::cout<<sizeof(newObject)<<std::endl;
}
int main()
{
char testChar = 'A';
printSize<testChar>();
return 0;
};
和幫助將不勝感激!
編輯:我還應該提到給定的隨機字符可以是任何字符值,并且型別別并不意味著使用 switch case 或 if else 陳述句顯式參考。
uj5u.com熱心網友回復:
您可以使用decltype如下所示:
printSize<decltype(testChar)>();
但注意testChar是一個char變數。另一方面,如果testChar是型別別變數,則將是該類的型別decltype(testChar)。例如,
A testChar;//testChar is of type A
printSize<decltype(testChar)>(); //decltype(testChar) is of type A
你也可以寫:
printSize<B>(); // directly write the name of the class that you want
uj5u.com熱心網友回復:
如果我理解正確,您想根據模板引數中提供的字符獲取類的大小。
遺憾的是,目前,在 C 中沒有簡單直接的方法可以做到這一點,因為它不支持反射(尚),但您可以手動將每個單獨的char值映射到相應的類并列印其大小:
#include <cstddef>
// ...
template <char X>
void printSize();
template <>
void printSize<'A'>() {
std::cout << sizeof(A) << std::endl;
}
// Do the same for 'B', 'C', 'D', etc...
// ...
然后你就可以這樣做:
// ...
int main() {
constexpr auto testChar = 'A';
printSize<testChar>();
return 0;
}
Demo
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/347884.html
上一篇:從串列向類添加屬性
