如何将函数指针声明指向模板函数,其返回类型取决于模板类

How to declare a function pointer to a template function whose return type is dependent on template class

本文关键字:函数 返回类型 取决于 指针 声明      更新时间:2023-10-16

标题听起来可能令人困惑,但这里有一些代码可以清除它,

template<class Act>
auto ActWrapper(Act && act, std::mutex mutex) -> decltype(act())
{
    //....
    return act();
}

如何编写函数指针以上函数?

没有模板函数指针,如果您正在寻找的话。如果您想将功能指针指向特定的实例化,则需要确切知道函数实例化的签名。

您总是可以用auto作弊:

auto ptr = &ActWrapper<foo>;

如果您不能使用auto,则需要知道返回类型:

return_t(*ptr)(foo&&, std::mutex) = &ActWrapper<foo>;
// or
decltype(ActWrapper(std::declval<foo>(), {}))(*ptr)(foo&&, std::mutex) = &ActWrapper<foo>;

如何编写函数指针以上函数?

您无法声明指向功能模板的功能指针。您只能声明函数指针指向功能。

如果Foo对于ActWrapper是有效的类型,则可以将功能指针声明为ActWrapper<Foo>。当时您会知道函数的返回类型,并且可以使用它。

using returntype = <the return type of Foo::operator()>;
using FuncionPtrType = returntype (*)(Foo&&, std::mutex);
FuncionPtrType functionPtr = ActWrapper<Foo>;

正如其他人指出的那样,您不能将简单的函数指针指向整个函数集,而仅用于模板的特定实例化。

如果您需要一些东西,则可以传递到整个集合,而不是特定的功能,则需要将其包裹在lambda或带有operator()的类中,然后将其转动。