How do you declare a template function a friend of a variadic class, both inside and outside the class declaration?
For example, this is how I'd think you'd write it inside the class declaration, but I'm getting an undefined reference error.
#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);
}
};
}
Friend functions do not inherit the template parameter.
#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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.