gpt4 book ai didi

c++ - enable_if + disable_if 组合引起模棱两可的调用

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:10 25 4
gpt4 key购买 nike

在尝试回答 this question 时我想建议使用 enable_if + disable_if允许基于类型是(或不是)多态这一事实来重载方法。

所以我创建了一个小的测试文件:

template <class T>
void* address_of(T* p,
boost::enable_if< boost::is_polymorphic<T> >* dummy = 0)
{ return dynamic_cast<void*>(p); }

template <class T>
void* address_of(T* p,
boost::disable_if< boost::is_polymorphic<T> >* dummy = 0)
{ return static_cast<void*>(p); }

struct N { int x; };


int main(int argc, char* argv[])
{
N n;
std::cout << address_of(&n) << std::endl;
return 0;
}

这看起来很温顺。

但是 gcc (3.4 ...) 对此感到窒息:

test.cpp: In function int main(int, char**):
test.cpp:29: error: call of overloaded address_of(N*) is ambiguous
test.cpp:17: note: candidates are: void* address_of(T*,
boost::enable_if<boost::is_polymorphic<T>, void>*)
[with T = N]
test.cpp:20: note: void* address_of(T*,
boost::disable_if<boost::is_polymorphic<T>, void>*)
[with T = N]

我的人类头脑似乎很清楚应该在这里使用哪种重载。我的意思是,我已经定义了一个替代方案,并且一次只能使用一个函数,这似乎很清楚……而且我本以为 SFINAE 会负责使不必要的重载无效。

我用 ... 修补了它(省略号)而不是 disable_if并且需要一个虚拟的第二个参数......但我仍然对为什么编译器对此感到窒息感兴趣。

最佳答案

编译器阻塞是因为您在 enable_ifdisable_if 上忘记了结尾的 ::type。模板总是被定义的;只是当且仅当表达式为 true(对于 enable_if)或 false 时,成员 type 才存在>(对于 disable_if)。

template <class T>
void* address_of(T* p,
<strong>typename</strong> boost::enable_if< boost::is_polymorphic<T> ><strong>::type</strong>* dummy = 0)
{ return dynamic_cast<void*>(p); }

template <class T>
void* address_of(T* p,
<strong>typename</strong> boost::disable_if< boost::is_polymorphic<T> ><strong>::type</strong>* dummy = 0)
{ return static_cast<void*>(p); }

如果没有尾部 ::type,您的函数模板只会创建重载,将指向 enable_ifdisable_if 实例的指针作为第二个参数.使用尾随的 ::type,模板要么创建具有 void* 类型的第二个参数的重载,要么删除重载(即所需的行为)。

关于c++ - enable_if + disable_if 组合引起模棱两可的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3491848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com