我有一個班級模板
template <class Key, class T, class Hash, template <class> class Allocator>
class Table;
和一個功能模板
template <class Key, class T, class DevHash, template <class> class DevAllocator, class HostHash, template <class> class HostAllocator>
void copyTableToHost(const Table<Key, T, DevHash, DevAllocator> &table, Table<Key, T, HostHash, HostAllocator> &hostTable);
現在我想授予對和copyTableToHost()的私有成員的訪問權限。為了做到這一點,我在課堂上做了一個朋友宣告:tablehostTableTable
template <class DevHash, template <class> class DevAllocator, class HostHash, template <class> class HostAllocator>
friend void copyTableToHost<Key, T, DevHash, DevAllocator, HostHash, HostAllocator>(const Table<Key, T, DevHash, DevAllocator> &table, Table<Key, T, HostHash, HostAllocator> &hostTable);
我的理由是我不需要在這里指定Key和T作為模板引數,因為這些對于給定的專業化是固定的。同時,給定的專業化需要與一整類函式成為朋友,這些函式的選擇不同, 和DevHash(DevAllocator我不確定模板模板引數是否不會在這里搞砸......)。HostHashHostAllocator
我得到的錯誤的形式member Table<Key, T, Hash, Allocator>::[member name] is inaccessible讓我相信朋友宣告沒有按預期作業。
uj5u.com熱心網友回復:
如果您希望它作為一個免費的friend功能模板,一種選擇可能是與它的所有實體成為朋友:
template <class Key, class T, class Hash, template <class> class Allocator>
class Table {
template <class K, class Ty,
class Hash1, template <class> class Allocator1,
class Hash2, template <class> class Allocator2>
friend void copyTableToHost(const Table<K, Ty, Hash1, Allocator1>& table,
Table<K, Ty, Hash2, Allocator2>& hostTable);
int x = 0; // private
};
template <class Key, class T,
class Hash1, template <class> class Allocator1,
class Hash2, template <class> class Allocator2>
void copyTableToHost(const Table<Key, T, Hash1, Allocator1>& table,
Table<Key, T, Hash2, Allocator2>& hostTable)
{
hostTable.x = table.x; // now ok
}
另一種選擇可能是改用迭代器并在成員函式中填充表,該函式接受迭代器,要求將迭代器解參考到std::pair<Key, T>- 或您用于打包每個類的任何類模板中<Key, T>。它可能看起來像這樣:
#include <type_traits>
#include <iterator>
template <class Key, class T, class Hash, template <class> class Allocator>
class Table {
public:
template<class It>
requires std::is_same_v<typename std::iterator_traits<It>::value_type,
std::pair<Key, T>>
void copyFrom(It first, It last) {
// copy from `first` to `last`
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531479.html
標籤:C 模板朋友
