可以在泛型类中为一种类型提供一个可用的函数

Possible to have a function available for one type in generic class?

本文关键字:一个 函数 类型 泛型类 一种      更新时间:2023-10-16

是否可以创建一个仅在使用特定类型实例化类时才可用的函数?(没有为该类型重写整个类?

如果我了解你所追求的是什么,一种可能性是使用包含其他函数的基类,然后有一个模板和一个都派生自该基类的专用化,专用化添加了您想要的额外函数:

struct X {
    int x() { return 1; }
};
template<class T>
struct Y : public X {
};
template<>
struct Y<int> : public X {
    int y() { return 2; }
};
int main() {
    Y<long> y;
    y.x();
    Y<int> z;
    z.y();
    return 0;
}