如何在不实例化A、B类的前提下确定重载函数f的返回类型?
问题:不实例化类的情况下确定重载函数的返回类型
给定以下代码,如何在不实例化A和B类的前提下,确定重载函数f两个版本的返回类型?
class A { public: A(std::string k) : key(k) { } private: std::string key; }; class B { public: B(int k) : key(k) { } private: int key; }; int f(const A&); std::string f(const B&); // 可以通过以下方式确定返回类型,但会实例化类: using a_return_type = decltype(f(A{ "" })); using b_return_type = decltype(f(B{0}));
最初的伪代码尝试
using a_return_type = std::invoke_result_t<f, A>; using b_return_type = std::invoke_result_t<f, B>;
编辑1:我需要不使用
A{ "" }和B{0}的解决方案,假设我不知道A和B的构造函数是什么。
编辑2:至少可以通过以下代码实现,但编码风格不佳:
A* p_a = nullptr; B* p_b = nullptr; using a_return_type = decltype(f(*p_a)); using b_return_type = decltype(f(*p_b));
或者更紧凑但同样不够优雅的写法:
using a_return_type = decltype(f(*static_cast<A*>(nullptr))); using b_return_type = decltype(f(*static_cast<B*>(nullptr)));
最优解决方案
可以使用std::declval(需包含<utility>头文件),它能在不调用构造函数的前提下生成指定类型的引用,完美适配需求:
#include <utility> using a_return_type = decltype(f(std::declval<const A&>())); using b_return_type = decltype(f(std::declval<const B&>()));
std::declval<T>()的作用是生成一个T&&类型的表达式,但我们可以直接将模板参数指定为const A&,这样就能精准匹配f的参数类型,全程不需要实例化A或B类,也无需知晓它们的构造函数细节。
内容的提问来源于stack exchange,提问作者Alexey Starinsky
相关产品推荐
相关产品推荐

