如何将模板函数作为模板类参数传递

How to pass a template function as template class argument?

本文关键字:参数传递 函数      更新时间:2023-10-16
事情

是这样的,似乎可以传递一个包含一些静态函数的模板化结构,如下所示:

template <class T> struct FunctionHolder {};
template <> struct FunctionHolder<string> {
    static void f(const string &s) {
        cout << "f call " << s << endl;
    }
};
template <class Key, class Value, class Holder = FunctionHolder<Key>>
class Foo {
  public:
    Foo(Key k) {
        Holder::f(k);
    }
};
int main(int argc, char *argv[]) {
    Foo<string, int> foo = Foo<string, int>("test_string");
}

但是,是否可以直接传递模板化函数而无需在模板化结构上静态定义?我已经试过了,它不会编译:

template <class string> static void f(const string &s) {
    cout << "f call " << k << endl;
}
template <class Key, class Value, typename func<Key>> class Foo {
  public:
    Foo(Key k) {
        func(k);
    }
};
int main(int argc, char *argv[]) {
    Foo<string, int> foo = Foo<string, int>("test_string");
}

问这个 cos 被迫创建虚拟结构(包含一堆静态函数的结构(用作主类的模板类型并不酷。

不幸的是,

函数模板不能用作模板模板参数;您可以使用函数指针作为非类型模板参数,例如

template <class Key, class Value, void(*func)(const Key&) = f<Key>> class Foo {
  public:
    Foo(Key k) {
        func(k);
    }
};