从“foo< T>到“const foo< const T>”。 - C ++ [英] Converting from "foo<T>" to "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< T>到“const foo< const T>”。 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!