如何在类声明的内部和外部声明模板函数是可变类的朋友?
例如,这就是我认为你在类声明中写的内容,但是我得到了一个未定义的引用错误。
#include <tuple>
#include <vector>
namespace ns
{
template<class...>
class Example;
template<class A, class... Bs>
std::vector<A>& get(Example<Bs...>& pExample);
template<class... As>
class Example
{
private:
std::tuple<std::vector<As>...> mVectors;
public:
explicit Example(std::size_t pCapacity)
: mVectors(std::vector<As>(pCapacity)...)
{}
template<class B> //Error: undefined reference to `std::vector<int,std::allocator<int> >& ns::get<int, int, float>(ns::Example<int, float>&)
friend std::vector<B>& get(Example<As...>& pExample)
{
return std::get<std::vector<B>>(pExample.mVectors);
}
};
}
答案 0 :(得分:3)
朋友功能不继承模板参数。
#include <tuple>
#include <vector>
namespace ns
{
template<class... As>
class Example;
template<class B, class... As>
std::vector<B>& get(Example<As...>& pExample);
template<class... As>
class Example
{
private:
std::tuple<std::vector<As>...> mVectors;
public:
explicit Example(std::size_t pCapacity)
: mVectors(std::vector<As>(pCapacity)...)
{}
template<class B, class... Cs> // <----
friend std::vector<B>& get(Example<Cs...>& pExample)
{
return std::get<std::vector<B>>(pExample.mVectors);
}
};
}
int main()
{
ns::Example<int,short,char> e(10);
auto v = ns::get<int>(e);
}