简体   繁体   中英

Passing default parameter to function C++

I want to call function either with default arguments or given by me, but default arguments are specified class private variables, simplified sample here:

Class::Something
{
public:
    void setI(int i);
private:
    void func(int i = this->i_default, j=this, k=this->k_default, l=this->l_default);

    int i_default; // May be different for different instances.
    int k_default; // May be different for different instances.
    int l_default; // May be different for different instances.
}

So when i call func() it takes default i_variable or when i call func(4) it takes 4 argument without changing i_default value. I know im doing something wrong couse i get error:

Error   1   error C2355: 'this' : can only be referenced inside non-static member functions or non-static data member initializer

is there some kind of way to achive such behaviour?

is there some kind of way to achive such behaviour?

Use function overload (Thanks @PiotrSkotnicki):

void func(int i);
void func() { func(i_default); }

The standard is quite clear about this. You explicitely cannot use this in the default parameter. You seem to be bound to use overloading for achieving this result:

void func(int i);
void func() { func(i_default); }

If you want to keep down the functions you could use a sentry that would allow func decide if it's to use the default. In the simpliest form:

void func(int* pi = NULL) {
    int i = pi ? *pi : i_default;

    // rest of the function
}

This method could be extended to use a helper class:

#include <cstdio>

template <typename C, typename T>
class Defaltable { 
    T val;
    T C::* ptr;

public:
    Defaltable(int C::* p) { 
        ptr = p;
        val = 0;
    }

    Defaltable(T x) {
        val = x;
        ptr = NULL;
    }

    T fetch(C* p) {
        return ptr ? p->*ptr : val;
    }
};

class Foo {
    int i_default;

public:
    Foo(int dflt) {
        i_default = dflt;
    }

    int func(Defaltable<Foo, int> x = &Foo::i_default) {
        return x.fetch(this);
    }
};


int main()
{
    Foo c(42);

    printf("%d\n", c.func(1));
    printf("%d\n", c.func());
}

You can declare i_default as const static (Thanks to @TartanLama ).

const static int i_default=1;

Here is the working program .

You can also use function overloading . But this uses less code than function overloading!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM