简体   繁体   中英

How to declare a const reference to function type

#include <iostream>
#include <type_traits>

void func()
{

}

int main()
{
  using T = const decltype(func) &;
  using T2 = void (&)();
  std::cout << std::boolalpha << std::is_same_v<T, T2> << std::endl;
}

How do you declare a const reference to a function type? The statement above prints true so I'm assuming that the const in T is ignored somehow. Is it possible at all to declare a const reference to a function type?

[dcl.fct]p7 :

The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored.

So you can only have a reference to a function, but not a const& as the const on a function type is ignored, as per above.

First of all, all references are constant . Once a reference has been initialized and bound to an object, it cannot be bound to another object. The reference is constant.

When we talk about "const reference", this in fact means a reference to a const object.

Is it possible at all to declare a const reference to a function type?

What does it mean for a free function to be const ? Nothing. Only non-static member functions can be const. No, it is not possible to have a reference to a constant function. Better yet, that const qualifier is ignored by the compiler, for good reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM