gpt4 book ai didi

c++ - 如何向可变类声明模板友元函数

转载 作者:行者123 更新时间:2023-11-30 02:24:56 25 4
gpt4 key购买 nike

如何在类声明的内部和外部将模板函数声明为可变类的友元?

例如,这就是我认为您会在类声明中编写它的方式,但我收到 undefined reference 错误。

#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);
}
};
}

最佳答案

友元函数不继承模板参数。

#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);
}

Live example

关于c++ - 如何向可变类声明模板友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45002134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com