如果两者都可行,编译器如何确定使用SFINAE的函数和标准函数之间的关系? [英] How does the compiler determine between a function using SFINAE and a standard function if both are viable?

查看:67
本文介绍了如果两者都可行,编译器如何确定使用SFINAE的函数和标准函数之间的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#include <iostream>
#include <type_traits>

template <typename T>
class A
{
public:
    // Allow func to be called if T is the const version of T2
    // e.g., T is 'int const' and T2 is 'int'
    template <typename T2,
              typename = typename std::enable_if<
                                          std::is_same<T, T2 const>::value>::type>
    void func(A<T2> const &)
    {
        std::cout << "Conversion" << std::endl;
    }

    // Allow func to be called for same version of T
    void func(A const &)
    {
        std::cout << "No conversion" << std::endl;
    }
};

int main()
{
    A<int const> a;

    a.func(A<int const>{});

    return 0;
}

使用GCC-8.3编译时,此代码会编译并生成输出没有转换-它选择了不使用 std :: enable_if func 的版本c $ c>。但是,如果我注释掉 func 的第二个版本,它仍将编译并产生输出 Conversion 。换句话说, A 中的 func 的两个版本均可用于此方法。鉴于这两种重载都是可行的,编译器用来选择 func(A const&)而不是其他版本( func(A< ; T2> const&))?

This code, when compiled with GCC-8.3 compiles and produces the output No conversion - it selected the version of func that does not use std::enable_if. However, if I comment out the second version of func, it will still compile and now produce the output Conversion. In other words, both versions of func within A are usable for this method. Given that both overloads are viable, what specific rule is the compiler using to select func(A const &) over the other version (func(A<T2> const &))?

推荐答案

规则是,如果非函数模板并且功能模板专长具有相同的签名,则选择非功能模板而不是模板专长。可以在 [over.match.best] / 2

The rule is that if a non function template and a function template specialization have the same signature, then the non function template is chosen over the template specialization. This can be found in [over.match.best]/2


鉴于这些定义,如果对于所有参数i ICSi(F1),则将可行函数F1定义为比另一个可行函数F2更好的函数。是比ICSi(F2)更糟糕的转换顺序,然后

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then

[...]


  • F1是不是功能模板专业化,而F2是功能模板专业化[...]

这篇关于如果两者都可行,编译器如何确定使用SFINAE的函数和标准函数之间的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆