Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What template parameter do I use? (C++ conceptual question)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading