static operator() in functor?

A

aaragon

Hi everyone,

Can someone point me out why I can't declare the operator() of a
functor as static? The reason behind this is that I want to be able to
call to the function without instantiating the Functor object. The
code is as follows:

#include <iostream>
using namespace std;

class Functor
{
public:

static void operator()(double c, double f){
cout<<"c -> "<<c<<endl;
cout<<"f -> "<<f<<endl;
}
};

int main()
{
Functor::eek:perator()(4,5);
return 1;
}

The error message is:
aaragon@aaragon-laptop:~/Desktop$ g++ test.cxx
test.cxx:9: error: 'static void Functor::eek:perator()(double, double)'
must be a nonstatic member function

Thank you.
 
I

Ian Collins

aaragon said:
Hi everyone,

Can someone point me out why I can't declare the operator() of a
functor as static?

An operator operates on an instance of a class.
 
J

James Kanze

Can someone point me out why I can't declare the operator() of a
functor as static?

Because the standard forbids it.

I don't think that there is any underlying technical reason, per
se; it would be easy for the compiler to implement. But what
would the operator syntax be if you didn't have an object; the
purpose of an overloaded operator is to be able to use the
operator syntax. Thus:

struct Toto
{
static void operator()() ; // suppose this were legal...
} ;

Toto aToto ;

aToto() ; // fine...
Toto::eek:perator()() ; // also OK.

// But how would use use the operator syntax without an
// object?

Given this, it makes "logical" sense to require it to be a
non-static member.
The reason behind this is that I want to be able to
call to the function without instantiating the Functor object. The
code is as follows:
#include <iostream>
using namespace std;
class Functor
{
public:
static void operator()(double c, double f){
cout<<"c -> "<<c<<endl;
cout<<"f -> "<<f<<endl;
}
};
int main()
{
Functor::eek:perator()(4,5);
return 1;
}
The error message is:
aaragon@aaragon-laptop:~/Desktop$ g++ test.cxx
test.cxx:9: error: 'static void Functor::eek:perator()(double, double)'
must be a nonstatic member function

The obvious solution: give the function a name, and call the
named function in your operator()(). The raison d'être of an
operator is to allow use with the operator syntax.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top