如何使用 C++11integral_constant::value_type()

Dea*_*hen 1 c++11

我正在学习使用 C++ 11 type_traits,在integral_constant中,有一个函数value_type();

我试过这个但有错误:

typedef std::integral_constant<int, 1> one_t;
one_t one_o;
one_o.value_type();
Run Code Online (Sandbox Code Playgroud)

../src/main.cc:13:9: 错误:不能用 '.' 引用'one_t'(又名'integral_constant')中的类型成员'value_type'
one_o.value_type();

Cas*_*eri 6

好吧,该函数 value_type()并不是真正具有该名称的函数。确实, 的定义是integral_constant这样的:

template <class T, T v>
struct integral_constant {
    // ...
    typedef T value_type;
    constexpr operator value_type() const noexcept { return value; }
};
Run Code Online (Sandbox Code Playgroud)

请注意,value_type它实际上是typedef模板参数的 a Tint在 OP 的示例中)。此外,还有一个转换运算符可以将 from 转换integral_constant<T, v>T。它是这样隐式调用的

int i = one_o; // same as int i = 1;
Run Code Online (Sandbox Code Playgroud)

要显式调用它,您需要使用operator关键字和正确的类型,如下所示:

one_o.operator int();
Run Code Online (Sandbox Code Playgroud)

多亏了typedef成员,这也相当于

one_o.operator one_t::value_type();
Run Code Online (Sandbox Code Playgroud)

  • 如果 `static constexprT value = val;` 已经在 `template &lt;typename T, T val&gt;` 中定义,为什么要提供 `operator value_type()`?@cassio-neri (2认同)