在模板中定义模板化友元函数 class
Defining a templated friend function inside a template class
为什么下面的代码会产生编译器错误no template named 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
的定义移到 class 之外并仅在 class.
中保留声明部分时,它正在工作
为什么不能直接在 class 中定义函数?
声明模板函数的唯一地方是在 class;它不在封闭命名空间中 "visible",因此不可用于正常查找,仅可用于参数相关查找。
您需要在 class 之外声明(并定义)它才能找到该函数,并将其声明为友元函数(如您所述)。
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...
为什么下面的代码会产生编译器错误no template named 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
的定义移到 class 之外并仅在 class.
为什么不能直接在 class 中定义函数?
声明模板函数的唯一地方是在 class;它不在封闭命名空间中 "visible",因此不可用于正常查找,仅可用于参数相关查找。
您需要在 class 之外声明(并定义)它才能找到该函数,并将其声明为友元函数(如您所述)。
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...