【问题标题】:Why does this of sfinae not work?为什么这个 sfinae 不起作用?
【发布时间】:2018-03-23 07:11:55
【问题描述】:
#include <type_traits>

using namespace std;

struct A
{
    using key_type = int;
};

template<typename T, typename = void>
struct has_key_type : false_type
{};

template<typename T>
struct has_key_type<T, decltype(typeid(typename T::key_type), void())>: true_type
{};

int main()
{
    cout << has_key_type<A>::value << endl;
    cout << has_key_type<int>::value << endl;
}

输出是:

1
0

正如预期的那样。但是,如果我从

decltype(typeid(typename T::key_type), void())

decltype(typeid(typename T::key_type), int())

如下:

template<typename T>
struct has_key_type<T, decltype(typeid(typename T::key_type), int())>: true_type
{};

输出是:

0
0

为什么第二个版本不起作用?

【问题讨论】:

  • 不相关,为什么要使用 typeid ?这仅用于运行时检查。
  • 使用int main,其中is standard
  • @liliscent 如果我没记错 typeid 只是对多态类型的运行时检查

标签: c++ templates sfinae typetraits compile-time-constant


【解决方案1】:

您没有提供第二个模板参数,因此它将使用默认模板参数,即void。在你的第二个版本中,decltype(typeid(typename T::key_type), int()) 的类型是int,所以has_key_type&lt;A&gt;,相当于has_key_type&lt;A, void&gt;,肯定不会匹配这个部分特化。

顺便说一句,从 C++17 开始,您可以使用 std::void_tdecltype(typeid(typename T::key_type), void()) 简化为 std::void_t&lt;typename T::key_type&gt;

【讨论】:

    猜你喜欢
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2013-03-10
    相关资源
    最近更新 更多