用通用函数指针参数化函数模板的简洁方法

Kon*_*rov 23 c++ templates decltype c++14

考虑以下案例:我有

int bar1();
double bar2();
Run Code Online (Sandbox Code Playgroud)

我想要:

foo<bar1>(); // calls bar1, then uses its result.
foo<bar2>(); // calls bar2, then uses its result.
Run Code Online (Sandbox Code Playgroud)

天真的写模板方式foo()是使用附加参数:

template <typename T, T (*f)()> void foo () {
  // call f, do something with result
}
Run Code Online (Sandbox Code Playgroud)

这有效,但我需要做丑陋的语法:

foo<decltype(bar1()), bar1>(); // calls bar1, then uses its result
Run Code Online (Sandbox Code Playgroud)

我想写一些漂亮的东西,就像上面一样foo<bar1>.

PS请不要建议在运行时接受参数.我只需要使用函数指针进行编译时参数化.

PS抱歉忘记提及:我正在寻找C++ 14解决方案.C++ 17赞赏,我赞成使用C++ 17解决方案,但项目现在使用C++ 14构建,我不能在最近的将来改变它.

Nat*_*ica 25

为了得到

foo<bar1>();
Run Code Online (Sandbox Code Playgroud)

你需要template<auto>从C++ 17.那看起来像

int bar1() { return 1; }
double bar2() { return 2.0; }

template<auto function> void foo() { std::cout << function() << "\n"; }

int main()
{
    foo<bar1>();
    foo<bar2>();
}
Run Code Online (Sandbox Code Playgroud)

哪个输出

1
2
Run Code Online (Sandbox Code Playgroud)

Live Example

在C++ 17之前,您必须指定类型,因为没有自动推断非类型模板参数的类型.