模板参数中使用的常量 & (ref)

const & (ref) used in template parameter

本文关键字:常量 ref 参数      更新时间:2023-10-16

我在一些代码中看到以下内容:

template<const Foo& bar>

有人告诉我,它的目的是处理大型结构。

那么我们不能在代码中直接使用常量和非模板化参数吗?
使用常量引用作为模板参数将对象引用作为参数传递是否是一种很好的做法?

这是一个非类型模板参数,恰好是 const Foo& 类型。

无论它的用途是什么("大结构"并不是那么描述性的),就像所有非类型模板参数一样,它的优点是在编译时可用(例如在元程序中),它的缺点是你必须在编译时有它的值。它是一个编译时常量,也可以帮助编译器更好地优化它。

以下是一些示例:

struct Foo {};
/////////////////////////////////
// Type template parameter :
template <class T>
struct TypeParame {
    T const &tRef; // T is a type
};
/////////////////////////////////
// Non-type template parameters :
// Integral type
template <int I>
struct NonTypeParam {
    // I is a value
    enum { constant = I };
};
// Reference
template <Foo const &F>
struct RefParam {
    // F is a value again
    Foo const &ref = F;
};
// Pointer
template <Foo const *F>
struct PtrParam {
    // F is still a value
    Foo const *ptr = F;
};
// More are possible, but...
// error: 'struct Foo' is not a valid type for a template non-type parameter
template <Foo F>
struct ValParam {};