c++ - 在非模板类中使用通用模板类

标签 c++ templates

我将在下面粘贴一些代码以更好地解释我的问题。

所以,我有这个名为Piece类模板:

template <typename T>
class Piece
{
public:
    Piece();
    ~Piece();
    //...
};

Piece 可以有两个不同的构造函数:

Piece<TextureMap::TileTextureID>::Piece()
    : m_texture(TextureMap::TileTextureID::INIT)
{
}

Piece<TextureMap::MeepleTextureID>::Piece()
    : m_texture(TextureMap::MeepleTextureID::BLUE)
{
}

另外,我有一个 class Foo,它有一个 bar 方法,如您所见,它通过 传递一个 Piece >引用

template <typename T>
class Piece;

class Foo
{
public:
    Foo();
    ~Foo();

private:
    void bar(Piece& piece); //ERROR!!!!
    //...
};

问题:

我理解错误。我需要通过键入以下内容来指定 Piece 的类型:

(Piece<TextureMap::TileTextureID>& piece);

(Piece<TextureMap::MeepleTextureID>& piece);

但这里的问题是,我希望它是通用的。我不想指定要传递给 bar 方法的 Piece 类型... 或者它是 TitleTextureIDMeepleTextureID。它可以是这两个选项中的任何一个...但是(重要)不要使 Foo 类也通用!

我怎样才能做到这一点?

错误:

error C2955: 'Piece' : use of class template requires template argument list

最佳答案

您只需将成员函数制作成成员函数模板即可。

template <typename T>
void bar(Piece<T>& piece);

这可以按照您期望的方式定义:

template <typename T>
void Foo::bar(Piece<T>& piece) { /* ... */ }

关于c++ - 在非模板类中使用通用模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33577651/

相关文章:

c++ - TagLib: 无法打开文件

c++ - 如何解决 requires 子句不兼容

c++ - std::functions 的复合模式

c++ - 使用模板参数时的交叉引用

c++ - OpenCV:H.264 编码视频的文件大小

c++ - 计算数组中位置的巧妙方法 (C++)

c++ - 在实时数据流上检测峰值

templates - 如何更改 phpstorm 自定义构造函数模板?

c++ - 如何实现非 constexpr `std::initializer_list` 样式构造函数

c++ - 为什么 `void* = 0` 和 `void* = nullptr` 会有所不同?