Byz*_*ian 2 c++ templates function-pointers variadic-templates c++11
我正在寻找一种方法将通用(constexpr,显然)功能传递给模板.它必须能够在不使用lambda的情况下获取任何数量的参数.这是我到目前为止:
template<typename T, T(*FUNC)()> struct CALL
{
static inline constexpr decltype(FUNC()) EXEC()
{
return FUNC();
}
};
Run Code Online (Sandbox Code Playgroud)
但是,只有传递的函数不带参数时才有效.有没有办法让模板接受任何constexpr功能?传递std ::函数似乎不起作用.我想关键是可变参数模板参数,但我不知道在这种情况下如何利用它们.
如果我正确理解您要实现的目标,则可以使用模板函数而不是具有静态函数的模板类:
#include <iostream>
template<typename T, typename... Ts>
constexpr auto CALL(T (*FUNC)(Ts...), Ts&&... args) -> decltype(FUNC(args...))
{
return FUNC(std::forward<Ts>(args)...);
}
constexpr double sum(double x, double y)
{
return (x + y);
}
int main()
{
constexpr double result = CALL(sum, 3.0, 4.0);
static_assert((result == 7.0), "Error!");
return 0;
}
Run Code Online (Sandbox Code Playgroud)