如何通过包装函数捕获第三方可变参数模板函数的实例化类型?
问题:捕获第三方可变参数模板函数的实例化类型
背景
我使用一个第三方可变参数模板函数:
template<typename...Types> void third_party_func(){}
调用方式为:
third_party_func<type_1, const type_2>();
我需要将这个函数包装到自定义函数中,借助__PRETTY_FUNCTION__捕获调用时传入的type_1, const type_2这些类型。
尝试过的写法与问题
- 最初的包装函数:
template<typename Funct> void registerFunct(Funct funct) { // 解析__PRETTY_FUNCTION__ funct(); }
调用代码:
registerFunct(third_party_func<type_1, const type_2>);
问题:__PRETTY_FUNCTION__无法捕获type_1, const type_2的具体类型。
- 模板模板参数写法1:
template<template<typename...FunctParams>typename Funct> void registerFunct(Funct funct){}
编译错误:argument list for template template parameter is missing
- 模板模板参数写法2:
template<template<typename...FunctParams>typename Funct> void registerFunct(Funct<> funct){}
问题:函数自身可编译,但传入实际实例化后的third_party_func时无法通过编译。
- 模板模板参数写法3:
template<template<typename...FunctParams>typename Funct> void registerFunct(Funct<FunctParams...> funct){}
编译错误:identifier FunctParams is undefined
解决方案
最直接的方式是让包装函数直接接收类型参数包,内部实例化第三方函数,这样__PRETTY_FUNCTION__会明确包含所有传入的类型:
template<typename... Types> void registerFunct() { // __PRETTY_FUNCTION__会显示Types...的具体类型,可在此解析 third_party_func<Types...>(); }
调用方式:
registerFunct<type_1, const type_2>();
如果必须保持传递函数对象的形式,可以通过显式指定类型参数来让__PRETTY_FUNCTION__捕获类型:
template<typename... Types> void registerFunct(void(*funct)()) { // __PRETTY_FUNCTION__会包含Types...的具体类型 funct(); }
调用代码:
registerFunct<type_1, const type_2>(third_party_func<type_1, const type_2>);
内容的提问来源于stack exchange,提问作者XORer
相关产品推荐
相关产品推荐

