Home > Enterprise >  Is it possible to acquire the function pointer of a template member function with not all template a
Is it possible to acquire the function pointer of a template member function with not all template a

Time:08-26

Considering the code below, is it possible to acquire the function pointer of operator() for Test2 given that you have all its template arguments? For example, say I want a function pointer that points to operator()<float, double> where Args={float} and Type2=double.

template<class Type1>
struct Test1 
{
    Type1 value;

    template<class Type2, class ... Args>
    bool operator()(const Type2& type) 
    {
        //... Do something with Args... //
        return type == value;
    }
};

template<class Type1>
struct Test2 
{
    Type1 value;

    template<class ... Args, class Type2>
    bool operator()(const Type2& type) 
    {
        //... Do something with Args... //
        return type == value;
    }
};

int main() 
{
    //OK! 
    auto ptr1 = &Test1<int>::template operator()<float, double>;
    //Not ok! Assuming here that Args = {float, double}, Type2 = ?. Want: Args = {float}, Type2 = double
    auto ptr2 = &Test2<int>::template operator()<float, double>;
}

I can see why just providing the template arguments to the function, as usual, doesn't work here. The template arguments are being deduced to be Args={float, double} and Type2 is left, hence a compilation error. This, I think, is evident from the fact that the Test1 version compiles perfectly fine. Is there a way around this? Thank you.

CodePudding user response:

you may try declaring it like this

bool (Test2<int>::*ptr2)(const double&) = &Test2<int>::template operator()<float>;

or even

auto ptr3 = static_cast<bool (Test2<int>::*)(const double&)>(&Test2<int>::template operator()<float>);
  •  Tags:  
  • c
  • Related