I tried to build a minimal example:
struct Functor
{
void operator()(int& a)
{
a += 1;
}
void other(int& a)
{
a += 2;
}
};
template <typename foo>
class Class
{
public:
void function()
{
int a = 10;
foo()(a);
std::cout << a << std::endl;
}
};
int main()
{
Class<Functor> c;
c.function();
}
My question about this: Why is it even possible to cal开发者_运维知识库l the operator on the pure type without an object? How can I call the function other
the same way as I call operator()
?
You're not calling it on a pure type. foo()
invokes the constructor, and evaluates to a temporary foo
object, on which you then invoke operator()
.
To do the equivalent with a "normal" member function, just do:
foo().other(a);
You are not "call[ing] the operator on the pure type without an object". The syntax foo()(a)
is creating a temporary of type foo
(this is the foo()
part) and then calling operator()
on that object with a
as argument: (the (a)
part).
Pure type example:
struct Functor
{
void operator()(int& a)
{
a += 1;
}
void other(int& a)
{
a += 2;
}
static void one_more(int& a)
{
a += 3;
}
};
template <typename foo>
class Class
{
public:
void function()
{
int a = 10;
foo()(a);
foo().other(a);
foo::one_more(a);
std::cout << a << std::endl;
}
};
int main()
{
Class<Functor> c;
c.function();
}
精彩评论