简体   繁体   English

可以从指向成员函数模板参数的指针推导出类类型

[英]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.

相关问题 Constexpr类模板成员函数与推导的void返回类型? - Constexpr class template member function with deduced void return type? C++11 能否从指针到成员模板参数中推导出 class 类型和成员类型 - Can C++11 deduce class type and member type from pointer-to-member template parameter 推导类型的基类成员的指针 - Deduced type for pointer-to-member of base class 在可变参数 function 模板中,可以从模板参数包元素中推断出返回类型 - In a variadic function template can the return type be deduced from the template parameter pack elements 为什么std :: function不能接受推导类型作为模板参数? - Why can std::function not accept a deduced type as its template parameter? 涉及非推导参数包的函数指针的参数类型的模板参数推导 - Template arguments deduction for parameter type of function pointer involving non-deduced parameter pack 模板参数接受指向类成员函数的指针 - Template parameter accepting pointer to class member function 模板类构造函数,以指向成员函数的指针作为参数 - template class constructor with pointer to member function as parameter 指向模板参数的类成员函数的指针 - Pointer to class member function of template parameter 使用已经推导出的模板参数来专门化模板成员函数 - Specialize template member function with already-deduced template parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM