从“foo< T>到“const foo< const T>”。 - C ++ [英] Converting from "foo<T>" to "const foo<const T>" - C++

查看:215
本文介绍了从“foo< T>到“const foo< const T>”。 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数像(请不要关心通过引用返回临时的,这只是一个例子来解释这个问题),

I have a function like (please don't care about returning temporary by reference. This is just an example to explain the problem),

const foo<const int>& get_const()
{
    foo<int> f;
    return f;
}

这显然不会编译。我正在寻找一种方法来确保呼叫者不会改变 foo T 。我如何确保?

This obviously won't compile. I am looking for a way to ensure callers won't change the T of foo. How can I ensure that?

我已经看到类似的行为 boost :: shared_ptr shared_ptr< T> 可转换为 const shared_ptr< const T> 。我不知道它是如何做的。

I have seen the similar behavior for boost::shared_ptr. shared_ptr<T> is convertible to const shared_ptr<const T>. I couldn't figure out how it is doing this.

任何帮助将是巨大的。

推荐答案

编译器将 foo< T> foo< const T> 不同的和不相关的类型,因此 foo 类需要支持这个显式,就像任何其他转换。如果你可以控制 foo 类,你需要提供一个拷贝构造函数或一个隐式转换运算符(或两者)。

The compiler sees foo<T> and foo<const T> as two completely different and unrelated types, so the foo class needs to support this explicitly just as with any other conversion. If you have control over the foo class, you need to provide a copy constructor or an implicit conversion operator (or both).

template<typename T>
class foo 
{
 public: 

   // Regular constructor
   foo(T t) : t(t) {}

   // Copy constructor (works for any type S convertable to T, in particular S = non-const T if T is const)
   // Remember that foo<T> and foo<S> are unrelated, so the accessor method must be used here
   template<typename S> foo (const foo<S>& copy) : t(copy.getT()) {}

   // Accessor
   T getT() const { return t; }

   // Conversion operator
   operator foo<const T> () const { return foo<const T>(t); }

 private:

   T t;
};

这篇关于从“foo&lt; T&gt;到“const foo&lt; const T&gt;”。 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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