为什么声明函数的顺序会更改SFINAE选择的重载? [英] Why does order of declaring function changes overload chosen by SFINAE?
问题描述
此问题与此答案有关。
在此示例中,FINA使用变量模板 has_literal_x
代替基本模板:
In this example SFINAE uses variable template has_literal_x
specialization instead of the base template:
struct A { };
A operator"" _x(char const*) { return {}; }
template<typename T, typename S, typename = void>
constexpr bool has_literal_x = false;
template<typename T, typename S>
constexpr bool has_literal_x<T, S,
std::enable_if_t<
std::is_same<
decltype(operator""_x(std::declval<S>())), T
>::value
>
> = true;
int main()
{
std::cout << has_literal_x<A, char const*> << std::endl; // 1
}
此处使用的是基本模板:
And here it uses the base template:
template<typename T, typename S, typename = void>
constexpr bool has_literal_x = false;
template<typename T, typename S>
constexpr bool has_literal_x<T, S,
std::enable_if_t<
std::is_same<
decltype(operator""_x(std::declval<S>())), T
>::value
>
> = true;
struct A { };
A operator"" _x(char const*) { return {}; }
int main()
{
std::cout << has_literal_x<A, char const*> << std::endl; // 0
}
在两个GCC上(第一,第二)和Clang(第一,第二)顺序来定义模板和用户文字更改,这些加载由SFINAE选择。为什么?
On both GCC (first, second) and Clang (first, second) order of defining templates and user literal changes which overload is chosen by SFINAE. Why?
推荐答案
这是沼泽标准两阶段查找问题的变体。对于依赖函数名称,
This is a variant of the bog-standard two-phase lookup question. For dependent function names,
- 不合格的查找仅考虑模板定义上下文
- 依赖于参数的查找同时考虑模板定义上下文和模板实例化上下文。
对于您的第二种情况,模板定义上下文中的不合格查找不会发现任何内容,并且 const char *
没有ADL。
For your second case, unqualified lookup in the template definition context finds nothing, and there's no ADL for const char *
.
这篇关于为什么声明函数的顺序会更改SFINAE选择的重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!