[英]Can class type be deduced from pointer to member function template parameter
Is it possible to deduce the type of the class T
from its pointer to memmber T::*f
as shown below. 是否可以从其指向memmber
T::*f
指针推导出类T
的类型,如下所示。
struct Foo
{
void func(){}
};
template<typename T, void (T::*f)()>
void bar()
{
}
int main()
{
bar<Foo,Foo::func>();
// bar<Foo::func>(); // Desired
}
In C++11/14 I would say no, unless you accept to deduce it by passing the pointer as a function argument: 在C ++ 11/14中我会说不,除非你接受通过将指针作为函数参数传递来推断它:
template<typename T>
void bar(void(T::*f)())
{
}
int main()
{
bar(&Foo::func);
}
In C++17 you can have a single parameter function template as shown by @Jarod42 , but you don't have the type T
deduced anyway (if it was the purpose, as it seems to be from the question). 在C ++ 17中,您可以使用@ Jarod42所示的单个参数函数模板,但是您还没有推导出类型
T
(如果它是目的,因为它似乎来自问题)。
If you have access to C++17, you can use auto
template parameter and decltype
to inspect the class type: 如果您有权访问C ++ 17,则可以使用
auto
template参数和decltype
来检查类类型:
struct Foo { void func(){} };
template<typename R, typename C, typename... Args>
C function_pointer_class(R (C::*)(Args...));
template<auto f>
std::enable_if_t<std::is_member_function_pointer_v<decltype(f)>>
bar() {
using class_t = decltype(function_pointer_class(f));
// stuff...
}
int main() {
bar<&Foo::func>();
}
In C++17, you will be allowed to write 在C ++ 17中,您将被允许编写
template<auto M>
void bar();
Which allows 这使得
bar<&Foo::func>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.