C++Guns – RoboBlog

14.03.2017

C++ Guns - Funktion return unterschiedliche lambda Funktionen

Filed under: Allgemein — Tags: — Thomas @ 06:03

Na sicher geht das. Zur Compilezeit wie auch zur Laufzeit.
Zur Compilezeit wäre if constexpr angebracht, aber das kann mein Compiler noch nicht. Mit Templates wär das wieder overload. Also nehm ich stink normales Funktion überladen mit Tags.


struct Add_tag {};
struct Mult_tag {};

auto func1(int x, Add_tag) {
    return [x](int y){ return x+y; };
}

auto func1(int x, Mult_tag) {
    return [x](int y){ return x*y; };
}

int main() {
    cout << func1(2, Mult_tag())(3) << "\n";
    return 0;
}

Zur Laufzeit fällt mir std::function ein. Mit den üblichen Performancefressern.


enum class Operator {ADD, MULT};

std::function func1(int x, Operator op) {
    switch(op) {
    case Operator::ADD:  return [x](int y){ return x+y; };
    case Operator::MULT: return [x](int y){ return x*y; };
    }
}

int main() {
    Operator op = Operator::MULT;
    cout << func1(2, op)(3) << "\n";
    return 0;
}

Hübsch? Naaah. Braucht man? Bisher nicht.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress