std::is_same - 来自integral_constant 的继承函数的用例

Phi*_*ZXX 3 c++ templates constexpr c++17

查看的实现std::is_same我们可以看到一些内部函数(继承自integral_constant)。为方便起见,让我复制 g++ 代码:

  template<typename _Tp, _Tp __v>
  struct integral_constant {
      static constexpr _Tp                value = __v;
      typedef _Tp                         value_type;
      typedef integral_constant<_Tp, __v> type;
      constexpr operator value_type()   const noexcept { return value; }
      constexpr value_type operator()() const noexcept { return value; }
  };

  template<typename, typename>
  struct is_same : public integral_constant<bool, false> { };

  template<typename _Tp>
  struct is_same<_Tp, _Tp> : public integral_constant<bool, true> { };
Run Code Online (Sandbox Code Playgroud)

这为我们提供了如何使用它的几个选项:

  bool a1 = is_same<int, int>{};               // instantiate & then cast implicitly
  bool a2 = is_same<int, int>();               // instantiate & then cast implicitly
  bool a3 = is_same<int, int>::value;          // use static member
  bool a4 = is_same<int, int>{}();             // instantiate & then use operator() 
  bool a5 = is_same<int, int>{}.operator()();  // instantiate & then use operator()
Run Code Online (Sandbox Code Playgroud)

我想知道这些额外功能有哪些用例,以及为什么像这样的简短实现

  template<class, class> constexpr bool is_same = false;
  template<class T> constexpr bool is_same<T,T> = true;
Run Code Online (Sandbox Code Playgroud)

不够?然后我们可以bool a = is_same<int,int>不用{}or()或来写::value

任何想法表示赞赏。

Bar*_*rry 5

这个问题的答案很大程度上是历史性的。类型特征比变量模板早了十年,因此您提出的选项是不合时宜的。出于可用性原因,其余部分是零碎添加的。


std::integral_constant早在 2003 年就通过N1424 引入。所以它是非常古老的技术,C++03 技术。当时,它是这样的:

template <class T, T v> 
struct integral_constant
{
   static  const T                value = v;
   typedef T                      value_type;
   typedef integral_constant<T,v> type;
};
Run Code Online (Sandbox Code Playgroud)

您没有看到任何其他成员函数,请注意,value它也只是static const,而不是static constexprconstexpr毕竟还没有。

许多年后,在 C++0x 的开发过程中,出现了一个库问题 ( LWG1019 ),考虑到新添加的constexpr,将其扩展为:

template <class T, T v>
struct integral_constant {
  static constexpr T value = v;
  typedef T value_type;
  typedef integral_constant<T,v> type;
  constexpr operator value_type() { return value; }
};
Run Code Online (Sandbox Code Playgroud)

此问题已由N2976解决。

转换函数的动机是它允许您使用类型的对象integral_constant作为这些值。对于某些元编程风格,如果您有一个返回的函数,比如true_type直接返回,您可以直接使用它:

std::true_type foo();    
if (foo()) { ... }
Run Code Online (Sandbox Code Playgroud)

而不是必须写if (foo().value)或其他类似的奇怪的东西。但是,对于非布尔常量,获取给定对象的值的唯一方法是访问value成员或进行显式转换(后者要求您知道类型):

constant.value
static_cast<???>(constant)
Run Code Online (Sandbox Code Playgroud)

这导致了N3545,在 2013 年,添加了调用运算符,允许您写入constant()以将值拉回来。最后这个添加真的有用吗?我不知道。

值得注意的是,所有这些都早于变量模板——其第一个修订版是N3615。您建议的is_same只是变量 bool 模板的选项直到后来才成为一个选项。即使使用可变模板,拥有不同类型也很方便,所以即使可能,我也不确定我们是否会走那条路。回想起来很难说。