I am going through the book C++ Crash Course by Josh Lospinoso and have been compiling the code in the lessons along the way. I’m having trouble with the following code (which is a simplified version of one of the examples in the book).
struct SmallStruct {};
template <typename T>
struct BigStruct {
BigStruct(const T& arg) : arg{arg} {};
private:
const T& arg;
};
int main() {
BigStruct main_struct{[](const SmallStruct&) {}};
}
The main part of this code I don’t understand is the statement in main(), specifically constructing with a lambda function. I know the code doesn’t compile because when instantiating the BigStruct object in main() it is lacking a template parameter. I’ve tried <SmallStruct>, <SmallStruct&> as parameters but neither compile. If anyone could explain what is going on it would be really beneficial for my learning.
>Solution :
In the "old" days the way was to use a make_... helper function to get the template parameter deduced from a function parameter:
struct SmallStruct {};
template <typename T>
struct BigStruct {
BigStruct(const T& arg) : arg{arg} {};
private:
const T& arg;
};
template <typename T>
BigStruct<T> make_big_struct(const T& t){
return {t};
}
int main() {
auto main_struct = make_big_struct([](const SmallStruct&) {});
}
Since C++17 there is CTAD (class template argument deduction) and your code compiles without error as is because T can be deduced from the parameter to the constructor (https://godbolt.org/z/oWrnc6bah).