gpt4 book ai didi

c++ - SFINAE 是否适用于功能体?

转载 作者:太空狗 更新时间:2023-10-29 20:39:37 26 4
gpt4 key购买 nike

我有以下示例代码:

class Serializable {};

class MyData : public Serializable {};

void GetData( Serializable& ) {}

template<typename T>
void GetData( T& data )
{
std::istringstream s{"test"};
s >> data;
}

int main()
{
MyData d;
GetData(d);
}

( Live Sample )

根据重载决议规则,非模板版本应该是首选,因为基类是 Serializable 类型。但是,我希望 SFINAE 在为重载决议实例化时模板版本中存在错误时启动(因为如果没有为类型定义 >> 运算符,则不应考虑)。

为什么不使用模板还是失败?

最佳答案

Based on overload resolution rules, the non-template version should be preferred because the base class is of type Serializable.

不完全是。 [over.match.best]:

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

  • for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that,
  • […]
  • F1 is not a function template specialization and F2 is a function template specialization […]

这意味着只有当函数模板的推导特化需要一个不比普通函数需要的转换更好的转换时,你的规则才适用。并且 dSerializable& 的绑定(bind)比 d 到 MyData& 的绑定(bind)更糟糕(这是特化的参数类型), [over.ics.ref]:

When a parameter of reference type binds directly (8.5.3) to an argument expression, the implicit conversion sequence is the identity conversion, unless the argument expression has a type that is a derived class of the parameter type, in which case the implicit conversion sequence is a derived-to-base Conversion (13.3.3.1).

However, I expect SFINAE to kick in when there are errors in the template version when it is instantiated for overload resolution (because if the >> operator is not defined for a type, it should not be considered).

SFINAE 不申请函数模板的内容。 [temp.deduct]/8:

Only invalid types and expressions in the immediate context of the function type and its template parameter types can result in a deduction failure.

因此确实选择了函数模板的推导特化,并在实例化其定义时导致编译器错误。

关于c++ - SFINAE 是否适用于功能体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27301135/

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