作为默认模板参数的具体函数

Concrete function as default template argument

是否可以在 C++ 中将具体(免费)函数设置为默认模板参数?

我的意思是这样的:

void foo() {}

template <typename F = foo>
struct C 
{
    F f;
};

函数指针是一个非类型模板参数。

template <auto F = &foo> // c++17
template <void(*F)() = &foo>

这是一个完整的例子:

#include <iostream>

void foo() { std::puts("foo"); }
void bar() { std::puts("bar"); }

template <void (*F)() = &foo>
struct Foo {
  void exec() { F(); }
};

int main() {
  Foo a;
  Foo<&bar> b;

  a.exec(); // prints "foo"
  b.exec(); // prints "bar"
}

如果您出于某种原因必须存储函数指针(就像您在代码片段中所做的那样),您可以通过将 decltype(F) f = F; 声明为 class 成员来实现。