仅通过参数查找重载地址
Find an overload address by its parameters only
假设一个函数(可以是全局函数或成员函数)仅在其参数上重载(因此其重载将始终是所有常量或所有非常量)。有没有办法编写一个模板,根据指定的参数选择重载地址?例如:
struct Foo {
double bar(double n, double m);
int bar(int n, int m);
};
auto addressDouble = find_overload<&Foo::bar, double, double>::address;
auto addressInt = find_overload<&Foo::bar, int, int>::address;
我在这里找到了一个有趣的答案,但不幸的是,它只处理将调用转发到正确的重载,而不是实际获取重载地址以便以后可以使用。
最后一点:一个完美的解决方案应该适用于已发布的 Clang 版本。除此要求外,还可以使用任何可用的 C++1z 及更低功能。
在访问重载函数的地址之前,您必须指定需要哪个版本。
template<typename ...TA>
struct find_overload
{
template<typename TObj, typename TR>
using member_func_t = TR(TObj::*)(TA...);
template< typename TObj, typename TR >
static constexpr auto get_address(member_func_t<TObj, TR> func) -> member_func_t<TObj, TR>
{
return func;
}
};
int main()
{
constexpr auto address = find_overload<double, double>::get_address(&Foo::bar);
}
您可以使用static_cast<>()
:
auto addressDouble = static_cast<double(*)(double, double)>(&Foo:bar);
auto addressInt = static_cast<int(*)(int, int)>(&Foo:bar);
尽管@MRB的工作答案,但存在更紧凑的解决方案。
它遵循一个最小的工作示例:
#include<iostream>
struct Foo {
double bar(double n, double m) {}
int bar(int n, int m) {}
};
double quux(double n, double m) {}
int quux(int n, int m) {}
template<typename... A, typename T, typename R>
constexpr auto find_overload(R(T::*f)(A...)) { return f; }
template<typename... A, typename R>
constexpr auto find_overload(R(*f)(A...)) { return f; }
int main() {
auto fooAddressDouble = find_overload<double, double>(&Foo::bar);
auto fooAddressInt = find_overload<int, int>(&Foo::bar);
Foo foo;
(foo.*fooAddressDouble)(0., 0.);
(foo.*fooAddressInt)(0, 0);
auto globalAddressDouble = find_overload<double, double>(&quux);
auto globalAddressInt = find_overload<int, int>(&quux);
globalAddressDouble(0., 0.);
globalAddressInt(0, 0);
}
如您所见,find_overload
同时接受自由函数和成员函数(它推导类类型和返回类型)。
相关文章:
- 重载运算符有地址吗?
- 重载 ostream << 运算符,指针作为参数,导致输出上的内存地址
- 重载函数的地址与所需类型不匹配
- 重载新返回错误的地址
- C++ - <<运算符重载,链表 - 地址而不是标准输出
- 错误:语句无法解析重载函数C++的地址
- 间接寻址运算符如何返回带有运算符重载的指针地址
- 重载运算符地址的用例
- 仅通过参数查找重载地址
- 推导模板类重载方法的地址会导致"error: expected primary-expression before ‘decltype’"
- 获取重载函数模板的地址
- C++重载运算符<<输出地址
- 在映射中插入地址时,新运算符重载会导致无限递归
- C++错误:语句无法解析重载函数的地址
- 编译器告诉我它无法解析重载函数的地址.对于 switch() 语句,这意味着什么
- 查找其 & 运算符重载且私有的对象的地址
- 匹配布尔值与常量 void* 重载的函数地址
- 使用指针数组中的对象调用重载的友元 ostream 插入运算符将返回内存地址
- 语句无法解析重载函数的地址
- 运算符打印地址<<重载