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?

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • 2
    You can use a variadic lambda `[] (auto... param) {}` like [described here](https://stackoverflow.com/a/26055639/10362622) – perivesta Jun 01 '22 at 11:36
  • 2
    Unfortunately it is very unlikely that a variadic lambda will work here, for some very, very fundamental reasons. – Sam Varshavchik Jun 01 '22 at 12:18

1 Answers1

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148