How to initialize variable(s) dynamically i.e. being not as constant, in class declaration which will be invoked/used without need of object instantiation such as a constructor for member function call immediately gets returned in a function ? There must, side by side of that variable(s) in that class, be a constant member.
enum Value :int { NO,LOW,MED,HIGH };
template<Value V> class valuation {
public:
valuation(s) : pos(s) {};
valuation(int a, int b, int c) : j(a), k(b), l(c) {};
value() {
if (!V)
return (j+k+l) * pos; }
private:
const int pos;
int j,k,l;
};
int main(){
// somehow in run-time j, k, l has been given 1,2,3, or other valid values
int v = a_function(7) // e.g.
}
int a_function(int s){
return valuation<NO>(s).value(); // no need object at all
int a_function(int s) {
return valuation<NO>(s).value(); // no need object at all
}
No. There is object. Unnamed, temporary object is created, used, and destroyed within that statement.
What do you need the class for? Why not just a function?
1 2 3 4 5 6 7 8 9 10
int value( Value V, int pos, int j, int k, int l )
{
if ( !V )
return (j+k+l) * pos;
elsethrow 42;
}
// use
int result = value( MED, 7, 5, 2, 3 );
You can (and should) initialize all members in a constructor:
1 2 3 4 5 6 7
template<Value V>
valuation<V>::valuation( int s, int a, int b, int c )
: pos(s), j(a), k(b), l(c)
{}
// use
int result = valuation<MED>( 7, 5, 2, 3 ).value();
From the point of view of the user (i.e. caller) you have data {NO, 7, 1, 2, 3} that you have to pass to a computation somehow and constness is not an issue, for you can have different data on every call.
The constness would make sense with long-living object:
1 2 3 4 5 6 7 8
valuation<MED> functor( 7, 5, 2, 3 );
for ( ... ) {
if ( /*something*/ ) {
functor.set_j( z );
}
result = functor.value();
// use result
}
The value() is called multiple times. For some calls the j (k or l) could change. The pos won't change.
There are of course the global variables (including class static members), but resorting to them reeks bad design most of the time.