Why does order of declaring function changes overload chosen by SFINAE?

╄→尐↘猪︶ㄣ 提交于 2019-12-07 15:48:30

问题


This question is related to this answer.

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
}

On both GCC (first, second) and Clang (first, second) order of defining templates and user literal changes which overload is chosen by SFINAE. Why?


回答1:


This is a variant of the bog-standard two-phase lookup question. For dependent function names,

  • Unqualified lookup considers only the template definition context
  • Argument-dependent lookup considers both the template definition context and the template instantiation context.

For your second case, unqualified lookup in the template definition context finds nothing, and there's no ADL for const char *.



来源:https://stackoverflow.com/questions/39781244/why-does-order-of-declaring-function-changes-overload-chosen-by-sfinae

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!