c++ - 使用函数指针专门化模板,这取决于模板参数

标签 c++ templates function-pointers

我想要一个带有嵌套值的模板,它应该由给定的初始化函数初始化:

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>{};

附加问题:为什么偏特化不能依赖于模板参数?此限制背后的基本原理是什么?

最佳答案

对于您的情况,您可以使用:

template <typename T>
T default_construct() { return T{}; }

template <typename T, T(INIT)() = &default_construct<T>>
struct Foo
{
    T value = INIT();
};

然后像这样使用它:

Foo<int> f;
Foo<int, bar> b;

Live demo

关于c++ - 使用函数指针专门化模板,这取决于模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528756/

相关文章:

c++ - boost::threads 示例和堆损坏消息

C++11 Lambda 和模板导致奇怪的链接器行为

c++ - 基于可变参数函数参数调用类函数会导致错误

传递函数指针的正确方式以及它们之间的区别

c - 带有/不带有 typedef 和显式参数声明的函数指针数组

c++ - 为什么我不能将函数指针作为模板参数传递给 map ?

c++ - 在 C++ 中,为什么我不能编写这样的 for() 循环 : for( int i = 1, double i2 = 0;

c++ - 使用迭代器 c++ 删除对象类型的 vector 元素

c++ - 增加 Stack Size 的缺点以及 Stack Commit 和 Reserve 之间的区别

latex - 在 LaTeX 中双倍行距 ACM session 论文