作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在类声明的内部和外部将模板函数声明为可变类的友元?
例如,这就是我认为您会在类声明中编写它的方式,但我收到 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);
}
关于c++ - 如何向可变类声明模板友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45002134/
我是一名优秀的程序员,十分优秀!