0

sqlite_modern_cpp examples

Usually we can output columns like this,

db << "select age,name,weight from user where age > ? ;"
         << 18
         >> [&](int age, string name, double weight) {
            cout << age << ' ' << name << ' ' << weight << endl;
         };

But if the column number is unsure select *, how do I write the lambda?

2
  • 2
    You can use a variadic lambda [] (auto... param) {} like described here Commented Jun 1, 2022 at 11:36
  • 2
    Unfortunately it is very unlikely that a variadic lambda will work here, for some very, very fundamental reasons. Commented Jun 1, 2022 at 12:18

1 Answer 1

0

if the column number is unsure select *, how do I write the lambda

That's the answer here: you can't. This is a fundamental rule of C++: the types of all objects are known at compile time. There are no exceptions.

This includes lambdas. A lambda is just an instance of an anonymous class with an operator() overload, that's what it really is. But it's still an instance of a discrete type that's defined at compile time.

You can look into this API and, perhaps, determine if it allows you to represent a variable number of columns in a resultset as a std::vector, or something similar. That would be one way to retrieve a list of an unknown number of columns at runtime, your lambda would then have to figure out what to do with them.

But in terms of enumerating columns as discrete parameters to a function or a lambda: that's up to you. You must specify explicit parameters, and their types, at compile time. C++ does not really work in any other way. Variadic lambdas, and templates, are just templates. Templates are not discrete types, they're just templates for types. They still need to be instantiated at compile time to a discrete type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.