将任何函数作为模板参数传递? [英] Passing any function as a template parameter?
问题描述
我正在寻找一种方法来传递一个通用(constexpr,明显)函数到模板。它必须能够采取任何数量的参数,而不使用lambda。这是我到目前为止:
I am looking for a way to pass a generic (constexpr, obviously) function to a template. It has to be able to take any amount of parameters, without using a lambda. This is what I have so far:
template<typename T, T(*FUNC)()> struct CALL
{
static inline constexpr decltype(FUNC()) EXEC()
{
return FUNC();
}
};
但是,这只有在传递的函数不带参数时才有效。有没有办法使模板接受任何constexpr函数?传递std ::函数似乎不工作。
我想关键是可变参数模板参数,但我不知道如何利用它们在这种情况下的优势。
This however only works if the passed function takes no parameters. Is there a way to make the template accept ANY constexpr function? Passing a std::function does not seem to work. I suppose the key is variadic template parameters, but I have no idea how to take advantage of them in this situation.
推荐答案
如果我正确理解你想要实现什么,你可以使用模板函数,函数:
If I understand correctly what you are trying to achieve, you can use a template function rather than a template class with a static function:
#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;
}
这篇关于将任何函数作为模板参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!