确定将类型作为引用传递时将调用哪个重载
Determine which overload will be called when passing type as reference
我有自由函数foo
这些函数对于用户定义的类型X
重载如下(C
是调用foo
的库类型):
template <typename C>
void foo(C&, const X&) {...}
我能够在编译时确定特定类型是否存在重载X
:
template <typename... Args>
auto foo_exists(int) -> decltype(std::bind<void(*)(Args...)>(&foo, std::declval<Args>()...), std::true_type());
template <typename... Args>
auto foo_exists(char) -> std::false_type;
struct Caller
{
template <typename T>
void call(const T& x)
{
static_assert(decltype(foo_exists<decltype(*this), const T&>(0))::value, "");
}
};
现在假设以下类层次结构具有Base
和Derived
的foo
重载:
struct Base{};
struct Derived : Base {};
struct Leaf : Derived{};
template <typename C>
void foo(C&, const Base&) { std::cout << "Base" << std::endl; }
template <typename C>
void foo(C&, const Derived&) { std::cout << "Derived" << std::endl; }
如何确定在调用foo(..., Leaf())
时,将调用const Derived&
重载?
一般而言:
我想测试foo
的确切类型,以找出特定X
类型的函数重载是否存在。 存在;如果不存在,我想知道基本类型的X
是否存在其他函数重载,如果是,在向其传递类型 const X&
的参数时会调用哪一个。
"which"信息应包含基类型,对于上述示例,基类型将是Derived
(而不是Base
)。
现场示例
您可以复制函数签名并编写自定义特征来检测将调用哪个特征,如下所示:
template <typename T>
struct S {
static Base mock_foo(const Base&);
static Derived mock_foo(const Derived&);
static void mock_foo(...);
// Base if Base overload will be called, Derived if Derived overload
// will be called, void if neither
using type = decltype(mock_foo(std::declval<T>()));
};
http://coliru.stacked-crooked.com/a/b72655b770becc15
我不确定是否可以"自动"执行此操作,即无需以这种方式键入自定义特征。我猜答案是否定的,它需要核心语言中的某种反射支持。
相关文章:
- 调用重载的"<大括号括起来的初始值设定项列表>"对于对来说就足够了是模棱两可的
- 为什么初始化时没有调用重载赋值运算符?
- 使用 MINGW gcc 编译时,不会为 std::string 调用重载的新运算符
- 为什么使用不匹配的参数调用重载函数仍然有效
- 无法弄清楚为什么没有调用重载运算符 []
- 使用 nullptr 调用重载方法是不明确的
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 在 if 语句中调用重载构造函数失败
- 为什么在析构函数中引发异常时不调用重载删除
- 从派生类调用重载函数
- 传递 const int* 和 int* 时调用重载函数的不同版本(const int* const&/&&)
- C++ - 在 std::thread 中调用重载函数时编译失败
- 为在与类方法中的类相同的命名空间中定义的结构调用重载运算符
- 从 C++ 中的子类调用重载父类的方法
- 在C++中,如何从父类变量的子类调用重载方法
- 使用指针调用重载而不分配新内存
- 如何在复制构造函数中调用重载的下标
- DetectMultiScale在使用rejectLevels和levelWeights调用重载时从不返回
- 从对象指针调用重载运算符 ()
- C++ 从类中调用重载运算符