在模板参数中使用 auto:一些使用示例和..如何使其与恒定大小的 C 数组一起使用



我在模板参数中对 auto 有以下示例性使用(我喜欢独立于它们的理智或是否存在更好的替代方案,我只是试图内化"模板参数中的自动"功能):

//1-Check if input is within open interval (l, h) where l & h are function parameters
//Example: int x = 5, y = fnc_y(), z = fnc_z(); auto fOk = gt_lt(z, x, y);
template<typename L, typename H, typename V> inline bool 
gt_lt(const V &v, const L& l, const H& h) { return (v > l) && (v < h); }
//2-Check if input is within open interval (l, h) where l & h are auto template parameters
//Example: int z = fnc_z(); auto fOk = gt_lt<5, 45>(z);
template<auto l, auto h, typename V>
inline bool gt_lt(const V &v) { return (v > l) && (v < h); }
//3-Fill a C array (a) of known size with a value where a is a function parameter: 
// char a[4]; fill_all(a, 'a');
template<typename TArrayValType, size_t N, typename TVal>
inline void fill_all(TArrayValType(&a)[N], const TVal &v) { std::fill(a, a + N, v); }
//4-Fill a C array (a) of known size with a value where a is an auto template parameter
//Can't figure out it!!! Goal: char a[4]; fill_all<a>('a');
template<auto a, **....what else to put it here?**, typename TVal>
inline void fill_all(const TVal &v) { std::fill(a, a + N, v); }

用法 No-4 不起作用。如何让它工作?我怀疑像在不知道其类型的情况下提取 SIZE 的值会起作用但仍然无法使其工作......

如上所述使用的一个动机是避免将某些值(当它们在编译时已知时)作为函数参数传递,即使在调试模式下也能获得更好的调试性能,或者希望有时在完全优化的构建中受益于它,如果由于非类型参数的 auto 而避免了参数传递,编译将生成更有效的代码。但是,然而,我仍然不确定这是否有意义......

据我所知,你不能这么简单。

正如您可以在此页面中阅读的

数组和函数

类型可以写在模板声明中,但它们会自动替换为指向对象的指针和指向函数的指针。

所以你可以写

template <auto a, typename TVal>
inline void fill_all(const TVal &v)
 { }
// ...
static int a[4] {};
fill_all<a>(2);

但是fill_all()a的类型视为int *,而不是int[4]

因此,您可以将其用作指针,但丢失了有关维度的信息。

我能想象的最好的是调用一个返回数组大小的constexpr函数,并将此值作为模板参数(或函数参数)

template <typename T, std::size_t N>
constexpr std::size_t getDim (T const (&)[N])
 { return N; }
template <auto a, std::size_t N, typename TVal>
inline void fill_all (TVal const & v)
 { std::fill(a, a + N, v); }
// ...
static int a[4] {};
fill_all<a, getDim(a)>(2);

但是,不幸的是,我没有看到避免显式模板参数列表中显式调用getDim()的方法。

相关内容

最新更新