- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在编写一个递归函数,其结束条件由模板参数确定。我正在使用 boost::enable_if
和 boost::disable_if
来切换空基本情况的递归函数(以防止令人厌烦的无限实例化循环)。
问题是它似乎取决于我定义这些函数的顺序:
#include <boost/utility.hpp>
template <unsigned a, unsigned b>
typename boost::disable_if_c<a == b>::type f()
{
f<a+1,b>();
}
template <unsigned a, unsigned b>
typename boost::enable_if_c<a == b>::type f()
{
}
int main()
{
f<0,5>();
}
编译器 (g++4.6) 失败并出现错误:
test.cpp:7:5: error: no matching function for call to ‘f()’
test.cpp:7:5: note: candidate is:
test.cpp:5:44: note: template<unsigned int a, unsigned int b> typename boost::disable_if_c<(a == b)>::type f()
由于某种原因,只有禁用的功能作为候选,没有看到启用的功能。
如果我切换这两个函数的定义顺序,它编译时会出现问题且不会出现警告:
#include <boost/utility.hpp>
template <unsigned a, unsigned b>
typename boost::enable_if_c<a == b>::type f()
{
}
template <unsigned a, unsigned b>
typename boost::disable_if_c<a == b>::type f()
{
f<a+1,b>();
}
int main()
{
f<0,5>();
}
这是为什么?到实例化发生时(在 main
中),编译器已经看到了这两个函数并且不应该关心谁先排队。至少我是这么想的。
最佳答案
你说
By the time the instantiation happens (in main) the compiler has seen both functions and shouldn't care who got in line first.
这不是真的,我认为这就是让你失望的原因。在 main 中实例化的只是 f<0,5>
,其余实例化发生在您调用它们的地方,首先在内部 f
函数模板。第二个从那里不可见,因此它不能参与过载决议。
那么,会发生什么:
// imagine we're inside f<4,5> instantiation
template <unsigned a, unsigned b>
typename boost::disable_if_c<a == b>::type f()
{
f<a+1,b>(); // <-- here we attempt to instantiate f<5,5> ...
// but it gets disabled!
// and there is no other f visible here, it's defined just below
}
如果切换定义顺序,enable_if
版本是可见的,它会在需要时启动。
关于c++ - Boost enable/disable_if 函数对的顺序很重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17002811/
在尝试回答 this question 时我想建议使用 enable_if + disable_if允许基于类型是(或不是)多态这一事实来重载方法。 所以我创建了一个小的测试文件: template
我正在编写一个递归函数,其结束条件由模板参数确定。我正在使用 boost::enable_if 和 boost::disable_if 来切换空基本情况的递归函数(以防止令人厌烦的无限实例化循环)。
Boost 同时拥有 enable_if 和 disable_if,但 C++0x 似乎缺少后者。为什么它被遗漏了? C++0x 中是否有元编程工具允许我根据 enable_if 构建 disable
我正在尝试构建模板类 Fod template class Fod { ... }; 它将包含一个带有 static const int value 的内部类 At指示模板参数的索引(S0 为 0,S
我是一名优秀的程序员,十分优秀!