Make function calls at compile time in C ++

Is there a way in C ++ to ensure that function calls are made at compile time so that this call is resolved:

obj.reset().setParam1(10).setParam2(20);

but this does not compile:

obj.reset().setParam1(10);

I want to avoid setting all the parameters in one function, since there are too many of them; therefore, I prefer to use something similar to idiom named parameters.

EDIT: An alternative syntax could be:

obj.reset(setParam1(10), setParam2(20));

or

obj.reset(setParam1(10).setParam2(20));
+4
source share
3 answers

The best I could do to provide both named parameters and force all initialized to execute is this.

template<typename T>
struct Setter
{
    Setter(const T &param) : ref(param) {}
    const T &ref;
};


typedef Setter<int> Param1;
typedef Setter<std::string> Param2;


struct CObj
{
    void reset(const Param1 &A, const Param2 &B) {
            setParam1(A.ref); setParam2(B.ref); }

    void setParam1(int i) { param1 = i; }
    void setParam2(const std::string &i) { param2 = i; }

    int param1;
    std::string param2;
};



int main()
{
    CObj o;
    o.reset(Param1(10), Param2("hehe"));
}
0
source

, . , ++ - idiom setter, ( ), .

+2

, , , . , , :

class Obj {
    Obj2 setParam2(int v);
}

class Obj2: public Obj {
    Obj2 setParam1(int v);
}

int main() {
    Obj obj;
    obj.setParam2(10); // possible
    obj.setParam2(10).setParam1(20); // possible
    obj.setParam1(20); // not possible
    obj.setParam1(20).setParam2(10); // unfortunately not possible

    // Edit: one more limitation- consecutive calls are not possible, 
    // you must chain
    obj.setParam2(20);
    obj.setParam1(10); // problem
}
+2

All Articles