"模板<class>好友类 Foo"是什么意思?
What does `template <class> friend class Foo` mean?
我正在探索boost::iterator_facade,并遇到了这段代码:
friend class boost::iterator_core_access;
template <class> friend class Iterator;
第二行是什么意思?我对朋友课很熟悉,但我想我以前没有见过template <class>
在任何东西前面。
上下文:
template <class Value>
class node_iter
: public boost::iterator_facade<
node_iter<Value>
, Value
, boost::forward_traversal_tag
>
{
public:
node_iter()
: m_node(0) {}
explicit node_iter(Value* p)
: m_node(p) {}
template <class OtherValue>
node_iter(node_iter<OtherValue> const& other)
: m_node(other.m_node) {}
private:
friend class boost::iterator_core_access;
template <class> friend class node_iter;
template <class OtherValue>
bool equal(node_iter<OtherValue> const& other) const
{
return this->m_node == other.m_node;
}
void increment()
{ m_node = m_node->next(); }
Value& dereference() const
{ return *m_node; }
Value* m_node;
};
typedef impl::node_iterator<node_base> node_iterator;
typedef impl::node_iterator<node_base const> node_const_iterator;
这意味着Iterator
是一个模板类,只有一个模板参数。Iterator
的所有实例都被授予友谊。
Iterator<int>
是班上的朋友。
Iterator<bool>
是班上的好朋友。
…
Iterator<MyClass>
是班上的好朋友。
你懂的。
假设你有一个类模板Foo
。
template <typename T> class Foo
{
public:
Foo() : data(0) {}
prvavte:
T data;
};
当您使用
实例化类模板时:Foo<int> a;
Foo<float> b;
在编译时创建两个类。Foo<int>
不能访问Foo<float>
的私有区,反之亦然。这有时很不方便。
你不能这样做:
b = a; // If you wanted to pull the data from a and put it in b.
即使在类中添加了赋值操作符,
template <typename T> class Foo
{
public:
Foo() : data(0) {}
template <typename T2> Foo& operator=(Foo<T2> const& rhs)
{
this->data = rhs.data;
return *this;
}
private:
T data;
};
它不会工作,因为Foo<T>
没有访问Foo<T2>
的私有部分。要解决这个问题,你可以使用友元声明。
template <typename T> class Foo
{
public:
template <class> friend class Foo;
Foo() : data(0) {}
template <typename T2> Foo& operator=(Foo<T2> const& rhs)
{
this->data = rhs.data;
return *this;
}
private:
T data;
};
现在,你可以使用:
Foo<int> a;
Foo<float> b;
b = a;
明确实例化:http://www.cplusplus.com/articles/1C75fSEw/
它允许你实例化模板而不实际使用它。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- C++中名称篡改的目的是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 派生类销毁的最佳实践是什么
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 通过JNI传递数据数组的最快方法是什么
- "using namespace std;"在C++的作用是什么?
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 文件系统:复制功能的速度秘诀是什么
- 在构造函数 foo() 中有一个模板是什么意思 <T>C++?
- "int& foo()"在C++中是什么意思?
- "模板<class>好友类 Foo"是什么意思?
- 在C++中,foo::bar::baz()的含义是什么