C++ 类型依赖模板的便捷using调用语法实现方案问询
结论
标准C++确实不支持你示例中type_dependent_template<int><T>这种直接的级联模板调用语法,但可以通过轻量的模板包装器实现完全等价的便捷调用效果,同时兼容你需要的传递模板模板参数的写法。
具体实现
核心包装代码
// 依赖模板的绑定包装器 template<typename T> struct type_dependent_template { // 用于直接实例化场景的内部别名 template<typename U> using type = typename TypeDependentTemplate<T>::template dependent_template<U>; }; // 直接实例化场景的便捷别名,省去写::type的步骤 template<typename T, typename U> using type_dependent_template_t = typename type_dependent_template<T>::template type<U>; // 如果需要支持直接把包装器传给接收模板模板参数的结构体(比如你的ExampleTemplateUse),加一个C++20概念特化即可 template<template<typename> typename T> struct ExampleTemplateUse {}; template<typename Wrapper> requires requires { typename Wrapper::template type<int>; } struct ExampleTemplateUse<Wrapper> : ExampleTemplateUse<Wrapper::template type> {};
用法验证
所有你期望的语法都可以正常工作:
// 等价于你示例中的Boo1 template<typename T> using Boo5 = type_dependent_template_t<int, T>; // 等价于你示例中的Boo2 template<typename T> using Boo6 = type_dependent_template_t<double, T>; // 等价于你示例中的Boo3,完全匹配你要的写法 using Boo7 = ExampleTemplateUse<type_dependent_template<int>>; // 等价于你示例中的Boo4,完全匹配你要的写法 using Boo8 = ExampleTemplateUse<type_dependent_template<double>>; // 你最后要求的实例化写法完全支持 ExampleTemplateUse<type_dependent_template<double>> my_obj;
如果你使用的是C++17及更早版本,不支持concept,只需要在传递模板模板参数时加::type即可,不需要修改原有的ExampleTemplateUse定义:
// C++17及更早版本的写法,语法差异极小 using Boo7_cpp17 = ExampleTemplateUse<type_dependent_template<int>::type>; using Boo8_cpp17 = ExampleTemplateUse<type_dependent_template<double>::type>;
内容的提问来源于stack exchange,提问作者Maximilian Keßler
相关产品推荐
相关产品推荐

