我想有这应该由给定的初始化函数初始化嵌套值模板:专营模板与函数指针,这取决于模板参数
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秒前回答的! –