Benny Smith
Benny Smith

Reputation: 249

Create static instead of a temporary for a function parameter

I'm looking for a bit of C++ syntax sugar here, if there's a way to do this. I have a class which maps a string to an int, and defines an int cast operator:

class C {
    public:
        C(const char * s) { m_index = /* value generated from s */; }
        operator int(void) const { return m_index; }
    protected:
        int m_index;
}

If I do the following:

void foo(int f);
...
static const C s_c("TEST");
foo(s_c);

The compiler invokes the constructor for C exactly once and reuses the int value obtained in every subsequent use of s_c; this is desirable behavior. My question is, is there some way to do:

foo(C("TEST"));

and have the compiler make a static, as above, rather than making a temporary and hitting the constructor every time the code is hit?

Thanks in advance.

Upvotes: 1

Views: 84

Answers (1)

Jeff
Jeff

Reputation: 3525

If you can use C++11, you can use constexpr to do transformations on literals:

// shamelessly copy-pasted from elsewhere
constexpr int some_hash(char const *in) {
  return *in ? static_cast<int>(*in) + 33 * some_hash(in + 1) : 5381;
}

Note that you have some pretty hefty restrictions though: no temporaries or statics, no access to outside variable, etc.

Upvotes: 1

Related Questions