如何通用地重新绑定单参数类模板的模板参数?
单参数类模板的通用参数重绑定方案
已知函数模板foo中变量t的类型基于某个单参数类模板,我们需要声明新变量other,复用这个类模板但传入不同的模板参数。如果类模板是可修改的自有代码,可以通过添加内置别名模板Self实现,示例代码如下:
template <typename T> struct Foo { template <typename U> using Self = Foo<U>; }; // bar是返回单参数类模板实例的函数(通用场景下可返回任意单参数类模板的实例) template <typename T> T bar(); template <typename T> void foo() { auto t = bar<T>(); // 复用t所属的类模板,传入int作为新参数声明other typename decltype(t)::template Self<int> other; }
但如果无法修改目标类模板的源码,我们可以通过模板萃取实现适配所有单参数类模板的通用方案:
通用解决方案代码
首先定义一个模板萃取器,用于从类模板实例中提取原始的类模板:
// 基础模板,用于匹配非单参数类模板的类型(此处无需实现) template <typename> struct template_extractor; // 针对单参数类模板实例的特化版本 template <template <typename> class Template, typename T> struct template_extractor<Template<T>> { // 提供参数重绑定的别名 template <typename U> using rebind = Template<U>; }; // 辅助别名,简化调用语法 template <typename InstanceType, typename NewParam> using rebind_template = typename template_extractor<InstanceType>::template rebind<NewParam>;
然后在foo函数中直接使用这个辅助别名即可:
template <typename T> void foo() { auto t = bar<T>(); // 复用t所属的类模板,传入int作为新参数声明other rebind_template<decltype(t), int> other; }
方案说明
这个萃取器通过模板特化机制,自动匹配所有单参数类模板的实例(比如Foo<int>、std::vector<int>这类单参数模板的实例),提取出原始的类模板(比如Foo、std::vector),再通过rebind别名实现参数替换。无论目标类模板是否内置了Self这类重绑定别名,只要它是单参数类模板,就能被这个方案适配。
内容的提问来源于stack exchange,提问作者geza
相关产品推荐
相关产品推荐

