考慮這兩個例子
示例 1
template<Type type>
static BaseSomething* createSomething();
template<>
BaseSomething* createSomething<Type::Something1>()
{
return Something1Creator.create();
}
template<>
BaseSomething* createSomething<Type::Something2>()
{
return Something2Creator.create();
}
.... // other somethings
例2
template<Type type>
static BaseSomething* createSomething()
{
if constexpr(type == Type::Something1)
{
return Something1Creator.create();
}
else if constexpr(type == Type::Something2)
{
return Something2Creator.create();
}
// Other somethings
}
我知道這兩個示例在概念上是相同的,但考慮到這些功能在一個SomethingFactory.hpp檔案中,我將其main.cpp包含在內。
在main.cpp我可能只創建型別Something1而不知道其他Something型別存在。
最后我真的很關心我的可執行檔案的大小。您認為我應該采用哪種模式使我的可執行檔案最小?或者這些都沒什么大不了的,反正我們都是注定的?
uj5u.com熱心網友回復:
您認為我應該采用哪種模式使我的可執行檔案最小?
在這兩種情況下,如果你只實體化createSomething<Type::Something1>你會得到一個函式定義,它實際上是一行代碼。
我真的很關心我的可執行檔案的大小
然后擺脫static. 模板函式是隱式行內的,但static函式對于每個翻譯單元都有唯一的副本。
我知道這兩個例子在概念上是相同的
他們不是。
createSomething<void>是使用Example2定義的函式,使用Example 1未定義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375298.html
標籤:C 模板 编译时 专业化 if-constexpr
上一篇:模板型別決議失敗
