我使用什么模板参数? (C++概念题)
What template parameter do I use? (C++ conceptual question)
我正在阅读 Josh Lospinoso 的 C++ 速成课程一书,并一直在编译课程中的代码。我在使用以下代码时遇到问题(这是书中示例之一的简化版本)。
struct SmallStruct {};
template <typename T>
struct BigStruct {
BigStruct(const T& arg) : arg{arg} {};
private:
const T& arg;
};
int main() {
BigStruct main_struct{[](const SmallStruct&) {}};
}
这段代码我不明白的主要部分是main()
中的语句,具体是用lambda函数构造的。我知道代码无法编译,因为在 main()
中实例化 BigStruct
对象时它缺少模板参数。我试过 <SmallStruct>
、<SmallStruct&>
作为参数但都没有编译。如果有人能解释一下发生了什么,那将对我的学习非常有益。
在“过去”的日子里,方法是使用 make_...
辅助函数来获取从函数参数推导的模板参数:
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&) {});
}
从 C++17 开始有 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).
我正在阅读 Josh Lospinoso 的 C++ 速成课程一书,并一直在编译课程中的代码。我在使用以下代码时遇到问题(这是书中示例之一的简化版本)。
struct SmallStruct {};
template <typename T>
struct BigStruct {
BigStruct(const T& arg) : arg{arg} {};
private:
const T& arg;
};
int main() {
BigStruct main_struct{[](const SmallStruct&) {}};
}
这段代码我不明白的主要部分是main()
中的语句,具体是用lambda函数构造的。我知道代码无法编译,因为在 main()
中实例化 BigStruct
对象时它缺少模板参数。我试过 <SmallStruct>
、<SmallStruct&>
作为参数但都没有编译。如果有人能解释一下发生了什么,那将对我的学习非常有益。
在“过去”的日子里,方法是使用 make_...
辅助函数来获取从函数参数推导的模板参数:
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&) {});
}
从 C++17 开始有 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).