我想用c++17自动推导出一个类(带有默认模板参数)typedef。有人知道这是否可能吗?下面的代码试图说明这一点:
#include <vector>
template <typename T = int>
struct A{
using Vec = std::vector<T>;
};
int main() {
A a{}; // works with c++ 17
A<int>::Vec vec2{}; //works
A::Vec vec{}; //does not seem to work with c++ 17. Is that possible somehow?
}
在上面的代码中,a
实例化没有问题,并且推导的模板类型默认为int
。尽管如此,我必须传递参数类型才能使用 typedef Vec
。如果有人知道以下两个问题的答案,我将不胜感激:
- 允许自动推断
A a{}
类型的功能的 ISO 邮件列表的论文编号/标题是什么?我很想了解有关此功能的更多信息。 - 是否可以在不显式指定
A
模板类型的情况下自动推断Vec
的类型?
非常感谢您的任何提示或建议!
最佳答案
Is it possible to infer the type of Vec automatically without specifying the template type of A explicitly?
是的。您可以留下<>
空:
A<>::Vec vec{};
否则,A
没有<>
或<int>
等,用未知的模板类型参数命名模板,并且您不能使用它来访问嵌套标识符。
What is the paper number/title of the ISO mailing list for the feature allowing automatic type deduction for A a{}? I am curious to learn more about this feature.
P1814是关于类模板参数推导(“CTAD”)的主要论文。 Here是 cpprefernece 上的页面。请注意A<>::Vec vec{}
不依赖 CTAD,因为不涉及执行实际推导的构造函数。
关于c++ - 如何为类特定的 typedef (c++17) 启用自动类型推导?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67870327/