我只是喜欢元编程,在youtube上看Cppcon频道,看到了这个std::integral_constant,但是找不到它的用途。
据我所知,它是一种将值与其类型一起“打包”的方法,可以用
std::integral_constant<int, 42> i;
std::integral_constant<bool, true> b;
std::integral_constant<float, 3.14> f;
...这些实例中的每一个都可以像它们包含的值一样使用,即:可以传递、用于数学操作、比较等。
但是,我不明白为什么我应该使用这些结构而不是实际包含的值,或者我是否能够在运行时实际访问值类型(即:int、bool和float)来处理它。
有人能给出一个简单的例子来说明这个特性的实际使用吗?一个解释它的用法与使用实际值不同的例子?
发布于 2020-10-11 10:04:55
std::integral_constant主要用作编写元编程特性的实用程序类型,特别是通过使用类型和值对类型进行编码。通过允许自定义特性继承std::integral_constant的专门化,我们可以通过静态成员常量value,以及通过成员类型value_type访问该常量的值类型,从而轻松、惯用地访问存储的非类型模板参数。
示例
例如,std::integral_constant可用于编写矩阵类型的维数特征。
using index_t = int;
template <index_t M, index_t N, typename S> struct mat {
// matrix implementation
};作为
#include <type_traits>
// Default dimensionality 0.
template <class T, typename = void>
struct dimensionality : std::integral_constant<index_t, 0> {};
template <typename S>
struct dimensionality<S, std::enable_if_t<std::is_arithmetic_v<S>>>
: std::integral_constant<index_t, 1> {};
template <index_t M, index_t N, typename S>
struct dimensionality<mat<M, N, S>> : std::integral_constant<index_t, M * N> {};
template <class T>
inline constexpr index_t dimensionality_v = dimensionality<T>::value;。
但是,一个更常见的用例是使用两种助手类型std::true_type和std::false_type来处理T是bool的常见情况。
类型定义
例如as
#include <type_traits>
struct Foo {};
template <typename T>
struct is_foo : public std::false_type {};
template<>
struct is_foo<Foo> : public std::true_type {};
template<typename T>
constexpr bool is_foo_v = is_foo<T>::value;
static_assert(is_foo_v<Foo>, "");
static_assert(!is_foo_v<int>, "");https://stackoverflow.com/questions/64302743
复制相似问题