To call a functor via A(3)
, then A
has to be the name of an variable, not the type. Which means A has to be either a instance of the functor, which ends up complicated because the functor type is public in which case you have to forbid others from constructing and copying and taking addresses and all that. Alternatively: make A a regular function.
functors.h
int A(int x);
functors.cpp
struct AFunctor {
int operator()(int x) const {return 3*x;} ;
};
int A(int x) {
static AFunctor a;
return a(x);
}
main.cpp
#include "functors.h"
int main()
{cout << A(3) << endl;}
As should be obvious at this point, there's literally no reason to have a singleton functor like this. Functors are usually stateful, or you can create them left and right, or both.
Since it's now clear that you definitely want singleton functors, this would be the way to go I guess.
functors.h
struct activation
{
virtual float operator() (float x) const = 0;
virtual float gradient (float x, float g) const = 0;
};
struct sigmoidFunctor : activation
{
float operator() (float x);
float gradient(float x, float g);
static sigmoidFunctor& get();
private
sigmoidFunctor()=default;
sigmoidFunctor(const sigmoidFunctor&)=delete;
};
extern sigmoidFunctor& sigmoid;
struct reluFunctor : activation
{
float operator() (float x);
float gradient(float x, float g);
static reluFunctor& get();
private
reluFunctor()=default;
reluFunctor(const reluFunctor&)=delete;
};
extern reluFunctor& relu;
functors.cpp
float sigmoidFunctor::operator() (float x)
{ return 1.f / (1.f + expf(-x)); }
float sigmoidFunctor::gradient(float x, float g)
{ float s = (*this)(x); return g * s * (1.f - s); }
sigmoidFunctor& sigmoidFunctor::get() {
static sigmoidFunctor sigmoid;
return sigmoid;
}
sigmoidFunctor& sigmoid = sigmoidFunctor.get();
float reluFunctor::operator() (float x)
{ return x; }
float reluFunctor::gradient(float x, float g)
{ return g; }
reluFunctor& reluFunctorFunctor::get() {
static reluFunctor relu;
return relu;
}
reluFunctor& relu = reluFunctor.get();
As evidenced by the vast increase in complexity, I strongly urge you to reconsider. Usually, singletons just make a mess of everything.