我想有這應該由給定的初始化函數初始化嵌套值模板:專營模板與函數指針,這取決於模板參數
template <typename T, T(INIT)()> struct Foo
{
T value = INIT();
};
可以這樣使用:
// Some random type only instanceable through factory()
struct Bar
{
int bar{};
private:
// The only way to create a Bar is through factory()
friend Bar factory();
Bar() {};
};
Bar factory() { return {}; }
Foo<Bar, factory> foo;
但是,如果沒有提供的功能,模板應儘量默認初始化嵌套的價值,所以我試圖專注模板:
template <typename T> struct Foo<T, nullptr>
{
T value{};
};
的想法是使用這種方式:
struct Baz{};
Foo<Bar, factory> foo; // Nested Bar have Bar::bar initialized through factory function.
Foo<Baz> baz; // No factory function needed, nested Baz default-initialized.
但我剛剛發現模板部分特例類型不能依賴於其他模板類型,我得到的錯誤被粘貼如下:
error: type 'T (*)()' of template argument 'nullptr' depends on a template parameter template struct Foo
有沒有辦法實現我的目標?
template <typename T, T(INIT)()> T Foo = INIT();
template <typename T> T Foo<T, nullptr>{};
額外的問題:爲什麼部分特例不能依賴於模板參數,如果它與模板變量的作品,以及這將是很好?這個限制背後的理由是什麼?
接受這一個,沒有從@ Jarod42中的一個,因爲它是在1秒前回答的! –