简体   繁体   English

防止左值引用绑定到非常量对象

[英]preventing binding of lvalue references to non-const objects

I'd like to prevent the binding of lvalue references to non-const objects to my function argument, currently I have this code: 我想防止将非常量对象的左值引用绑定到我的函数参数,目前我有以下代码:

template <typename T>
using remove_cr = std::remove_const<typename std::remove_reference<T>::type>;

template <typename T>
using is_nc_lvalue_reference
  = std::integral_constant<bool,
      std::is_lvalue_reference<T>::value
      && !std::is_const<typename std::remove_reference<T>::type>::value
    >;

template <typename T>
void func(T && v, typename std::enable_if<
  std::is_same<THE_TYPE_I_WANT, typename remove_cr<T>::type>::value
  && !is_nc_lvalue_reference<T>::value>::type* = 0)
{
}

This seems a tremendous lot of code to me, does there exist a more elegant SFINAE or non-SFINAE method? 在我看来,这似乎是很多代码,是否存在更优雅的SFINAE或非SFINAE方法? I don't need perfect forwarding, but if I don't use it, I lose T . 我不需要完美的转发,但是如果我不使用它,则会丢失T

The idea is, that const objects should not be modified, hence I can convert them to some other representation and feed them, say to a different process. 这个想法是,不应该修改const对象,因此我可以将它们转换为其他表示形式,并提供给不同的进程。 If a non-const reference is given, the object it references can be modified, but the other process does not have access to memory space of the forwarding process and hence I don't forward it. 如果给出了非常量引用,则可以修改其引用的对象,但是其他进程无法访问转发进程的内存空间,因此我不转发它。

How about this: 这个怎么样:

template <typename T>
void func(const T &x) {
  process(x);
}

template <typename T>
void func(T &x) {
  do_nothing(x);
}

Example in action. 实际的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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