模板参数中使用的常量 & (ref)
const & (ref) used in template parameter
我在一些代码中看到以下内容:
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 {};
相关文章:
- #定义c-预处理器常量..我做错了什么
- 对RValue对象调用的LValue ref限定成员函数
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 将Ref对象作为类成员
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我可以通过引用修改常量返回
- 为什么我的 std::ref 无法按预期工作?
- 如何创建长度由常量参数指定的数组
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 模板参数中使用的常量 & (ref)