gpt4 book ai didi

C++11 风格的 SFINAE 和模板实例化的函数可见性

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

我不确定这是否与 sfinae 有任何关系,或者只是与任何模板函数相关的事情。我正在尝试使用 sfinae 根据相应自由函数的存在来启用/禁用成员函数,而该成员函数又根据另一种类型的成员函数的存在来启用/禁用,所有这些都使用描述的方法 here :

struct S;

template <typename T>
inline auto f(S& s, T const& t)
-> decltype(t.f(s), void())
{
t.f(s);
}

struct S
{
template <typename T>
auto f(T const& t)
-> decltype(f(*this, t), void())
{
f(*this, t); // <------------------------------------------- HERE
}
};

struct pass
{
void f(S&) const
{
//...
}
};

struct fail
{
};

int main()
{
S s;
s.f(pass()); // should compile fine
//s.f(fail()); // should fail to compile due to absence of f from S
return 0;
}

但是 gcc 4.7.1 在箭头标记的行上给了我这个:

error: no matching function for call to 'S::f(S&, const pass&)'
note: candidate is:
note: template decltype ((f((* this), t), void())) S::f(const T&)
note: template argument deduction/substitution failed:
note: candidate expects 1 argument, 2 provided

这显然意味着上面的全局 f 不被考虑用于重载决议。

为什么会这样,我该怎么做才能做到这一点?

另外,为什么上面两行没有错误,其中 f 以类似的方式在 decltype 中使用?

更新

作为@n.m.据说,成员函数完全没有影子函数,即使它们的签名不同,所以这里有一个不会破坏 f 的 ADL 的解决方法(与 @n.m. 建议的全名限定不同)。在没人会看到的地方创建自由函数 (f_dispatcher) (detail),并在 S::f 中完全限定其名称。在该函数中调用 free f 并让 ADL 从那里开始处理它,如下所示:

struct S;

template <typename T>
inline auto f(S& s, T const& t)
-> decltype(t.f(s), void())
{
t.f(s);
}

namespace detail
{
template <typename T>
inline auto f_dispatcher(S& s, T const& t)
-> decltype(f(s, t), void())
{
f(s, t);
}
}

struct S
{
template <typename T>
auto f(T const& t)
-> decltype(detail::f_dispatcher(*this, t), void())
{
detail::f_dispatcher(*this, t);
}
};

struct pass
{
void f(S&) const
{
//...
}
};

struct fail
{
};

int main()
{
S s;
s.f(pass()); // compiles fine
//s.f(fail()); // fails to compile due to absence of f from S
return 0;
}

最佳答案

这与 SFINAE 或模板、C++11 或 ADL 无关。

一个成员隐藏所有同名的非成员,无论类型如何。如果您有一个名为 f 的成员,则不能引用任何名为 f 的非成员,除非您使用限定名称(例如 ::f).

只需使用 ::f(*this, t);

关于C++11 风格的 SFINAE 和模板实例化的函数可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11694970/

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