gpt4 book ai didi

c++ - 专门化成员 S::display 需要 ‘template<>’ 语法

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:54 25 4
gpt4 key购买 nike

我正在创建一个特征类来帮助我的程序。我有一个名为 operations 的模板类包含方法 displayarea .当我定义这些函数时,我得到了错误。他们在这里:

error: specializing member ‘traits::operations<Rectangle>::display’ requires ‘template<>’ syntax
error: specializing member ‘traits::operations<Rectangle>::area’ requires ‘template<>’ syntax

如您所见,编译器要我插入 template <>就在这些定义之前。但是当我这样做时,我会收到一大页错误。出了什么问题,我该如何解决?

这是我的程序。

namespace traits
{
template <typename P>
struct operations
{
static void display(Rectangle const &, std::ostream &);
static void area(Rectangle const &);
};

template <typename P, int N>
struct access {};
}

namespace traits
{
template <int N>
struct access<Rectangle, N>
{
static double get(Rectangle const &);
};
}

// The errors occur here
namespace traits
{
static void operations<Rectangle>::display(Rectangle const &rect, std::ostream &os)
{
os << rect.width << '\n';
os << rect.height << '\n';
os << area(rect) << '\n';
}

static void operations<Rectangle>::area(Rectangle const& rect)
{
double width = get<0>(rect);
double height = get<1>(rect);

return width * height;
}
}

namespace traits
{
template <>
struct access<Rectangle, 0>
{
static double get(Rectangle const &rect)
{
return rect.width;
}
};

template <>
struct access<Rectangle, 1>
{
static double get(Rectangle const &rect)
{
return rect.height;
}
};
}

template <int N, typename P>
static inline double get(P const &p)
{
return traits::access<P, N>::get(p);
}

template <typename P>
static inline void display(P const &p)
{
traits::operations<P>::display(p, std::cout);
}

template <typename P>
static inline double area(P const &p)
{
return traits::operations<P>::area(p);
}

int main()
{

}

这是一个显示错误的程序 - http://ideone.com/WFlnb2#view_edit_box

感谢任何帮助。


感谢评论的帮助,我摆脱了这两个错误,但在添加 template<> 后我并没有得到更多声明并修复 area 的返回类型:

error: cannot declare member function ‘static void traits::operations<P>::display(const Rectangle&, std::ostream&) [with P = Rectangle; std::ostream = std::basic_ostream<char>]’ to have static linkage [-fpermissive]
error: explicit template specialization cannot have a storage class
error: specialization of ‘static double traits::operations<P>::area(const Rectangle&) [with P = Rectangle]’ after instantiation
error: explicit template specialization cannot have a storage class

最佳答案

您的功能:displayarea应该这样写:

    template <>
double operations<Rectangle>::area( Rectangle const& rect )
{
double width = get<0>(rect);
double height = get<1>(rect);

return width * height;
}
  • 至于模板专用函数,template <>应该放在在函数的头部。
  • 对于静态成员函数,static不应该出现在函数的定义体。

关于c++ - 专门化成员 S::display 需要 ‘template<>’ 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493187/

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