为什么以下代码产生编译器错误没有名为make_static_vector的模板?
template<class Tuple>
class vector;
template<typename T, std::size_t N>
using static_vector = vector<std::array<T, N>>;
template<class Tuple>
class vector
{
private:
using value_type = std::decay_t<decltype(std::declval<Tuple&>().operator[](0))>;
template<typename T, typename... Elements>
friend static_vector<T, sizeof...(Elements)> make_static_vector(Elements&&... elements) {
return { std::forward<Elements>(elements)... };
}
template<typename... Elements>
vector(Elements&&... elements)
: m_elements{ static_cast<value_type>(std::forward<Elements>(elements))... }
{ }
Tuple m_elements;
};
int main()
{
make_static_vector<double>(1, 1);
return 0;
}
我创建了一个live demo of the code.当我在类外部移动make_static_vector的定义并且只将声明部分留在类中时,它正在工作.
为什么不能直接在类中定义函数?
解决方法:
声明模板函数的唯一地方是在类中;它在封闭命名空间中不是“可见的”,因此不能用于正常查找,仅用于参数依赖查找.
您需要在类外面声明(并定义)它以查找要找到的函数,并将其声明为友元函数(如您所述).
A name first declared in a friend declaration within class or class template X becomes a member of the innermost enclosing namespace of X, but is not accessible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided…