gpt4 book ai didi

c++ - Boost enable/disable_if 函数对的顺序很重要吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:03 24 4
gpt4 key购买 nike

我正在编写一个递归函数,其结束条件由模板参数确定。我正在使用 boost::enable_ifboost::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/

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