What’s the meaning of &T::operator() in function traits?

What’s the meaning of &T::operator() in function traits?


6

// Fallback, anything with an operator()
template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> > {
};

What does T::operator() mean here?

This is code from pytorch.

Share
Improve this question

New contributor

ben19900305 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2 Answers
2

Reset to default


8

&T::operator() is a pointer to member function. In this case it’s a pointer to typename T‘s operator() member function.

To give this a concrete grounding, consider this minimal definition of T:

struct T
{
    int operator()(int x) { return x * 2; }
};

We could save a pointer to the member function in a variable:

auto pmf = &T::operator();

And we can call it:

T object;
int four = (object.*pmf)(2);

Share
Improve this answer


0

The function call operator allows an object to be called as a function.

e.g.

#include <iostream>
#include <string>

class Howdy {
   std::string name_;
public:
   Howdy(const std::string& name) : name_(name) {}
   void operator()() const { // <- this is "operator()"
        std::cout << "Hello " << name_ << std::endl;
   }
};

int main() {
    Howdy howdy{"world"};
    howdy(); // Outputs "Hello world"
}

Share
Improve this answer

1

  • 2

    This doesn't really explain what the expression &T::operator() does, what type it creates, and how it is relevant to traits.

    – Jan Schultke

    14 hours ago



Not the answer you're looking for? Browse other questions tagged

or ask your own question.

Leave a Reply

Your email address will not be published. Required fields are marked *