使用左值引用作为非类型模板参数 [英] Using an lvalue reference as a non-type template parameter

查看:31
本文介绍了使用左值引用作为非类型模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到允许以下类型作为非类型模板参数:

I read that the following types are allowed as non-type template parameters:

  • 整体类型
  • 枚举
  • 指向对象/方法的指针
  • 对对象/方法的左值引用
  • std::nullptr_t

我不明白如何接受非常量指针或左值引用?它们不应该是常量类型以便在编译时识别它们吗?

I don't understand how a non constant pointer or a lvalue reference is acceptable? Shouldn't they be constant types so that they are identified at compile time?

显然我并不比标准更聪明,所以有人可以向我展示一个左值引用的例子,也许一个指针被用作非模板参数?

Obviously I'm no smarter than the standard so can someone show me an example of an lvalue reference and maybe a pointer being used as non template parameter?

推荐答案

下面是一个同时具有方法指针和左值引用作为非类型模板参数的示例:

Here's an example which has both a method pointer and an lvalue reference as non-type template parameters:

int delete_counter_1 = 0;
int delete_counter_2 = 0;

template<int& ctr>
void increment_counter() { ++ctr; }

template<void(*func)()>
class Deleter {
    public:
    ~Deleter() { func(); }
};

int main() {
    { /* Internal scope */
      Deleter<increment_counter<delete_counter_1>> a, b;
      Deleter<increment_counter<delete_counter_2>> c;
    }
    std::cout << "Counter1: " << delete_counter_1
              << "; Counter2: " << delete_counter_2
              << '\n';
    return 0;
}

coliru 上查看.

Deleter 类的有趣之处在于它没有实际的数据成员;其析构函数可以直接内联,无需间接函数调用.

The interesting thing about the Deleter class is that it has no actual data members; its destructor can be directly inlined without indirect function calls.

正如 Dalibor Frivaldsky 在评论中提到的,关键是(实例化的)函数 delete_counter 和计数器本身在编译时具有已知的固定地址,所以 作为指针 它们的值是常量.特别是,这仅适用于具有静态生命周期的对象;自动(堆栈分配")对象不起作用,非静态类成员也不起作用,但静态对象(如上)和静态类成员就可以了.

As mentioned by Dalibor Frivaldsky in a comment, the point is that the (instantiated) functions delete_counter<int&> and the counters themselves have fixed addresses known at compile-time, so as pointers their values are constant. In particular, this is only true for objects with static lifetime; automatic ("stack-allocated") objects wouldn't work, and neither would non-static class members, but static objects (as above) and static class members are just fine.

这篇关于使用左值引用作为非类型模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆