在模板参数中使用 {} 在 type_trait{} 中时,其作用是什么<T>?

What is the role of the {} in type_trait<T>{} when used in a template parameter?

本文关键字:作用 是什么 gt lt trait 参数 type 中时      更新时间:2023-10-16

我经常在模板化代码中看到这种{}的出现。我不确定我是否理解它在做什么。例如:

std::enable_if_t<std::is_copy_constructible<T&>{} && !std::is_same<T, MyClass>{}>>

这里{}是什么?它是否实例化类型?作为模板参数,这意味着什么?

AFAIK 实例化类型意味着创建对象。如何在此上下文中创建对象?它只是创建一个虚拟对象吗?为什么要这样做呢?这有什么意义和目的?

在这种情况下,type_trait<T>{}等同于type_trait<T>::value。您的示例等效于以下内容:

std::enable_if_t<std::is_copy_constructible<T&>::value && !std::is_same<T, MyClass>::value>>

通常,使用type_trait<T>{}而不是type_trait<T>::value的一些好处是:

  • C++17 增加了type_trait_v<T>.在C++17之前,type_trait<T>{}同样简洁。
  • type_trait<T>{}适用于标记调度。也就是说,foo(type_trait<T>{})可以根据type_trait<T>::value的值调用不同的重载,因为真值和假值是不同的类型。

这是有效的,因为类型特征继承自std::integral_constant<bool, Value>,具有返回值的constexpr operator bool()。因此,std::is_copy_constructible<T&>{}产生一个类型为std::is_copy_constructible<T&>的值,但由于我们在需要bool的上下文中使用它,因此调用隐式转换运算符。