相关疑难解决方法(0)

无法将null函数指针作为模板参数传递

我想将一个函数作为模板参数传递给另一个函数,以便以后可以存储和调用它.在某些情况下,我想为回调传递NULL,但我遇到了麻烦.以下是我希望能够做到的一个例子:

#include <iostream>
struct Foo {
    int i;
};
template <typename T>
T* T_new() {
    return new T();
}
Foo* Foo_new() {
    return new Foo();
}
template <typename T, T* (*func)()>
T* T_new() {
    if (func)
        return func();
    else
        return NULL;
}

int main(void) {
    // Works
    Foo* f1 = T_new<Foo>();
    std::cout << f1 << std::endl;

    // Works
    Foo* f2 = T_new<Foo, Foo_new>();
    std::cout << f2 << std::endl;

    // fails to compile, "no matching function for call to ‘T_new()’"
    // …
Run Code Online (Sandbox Code Playgroud)

c++ templates

9
推荐指数
1
解决办法
2622
查看次数

标签 统计

c++ ×1

templates ×1