在不指定实例化的情况下调用类模板的静态方法的方法

Way to call a static method of a class template without specifying an instantiation?

本文关键字:方法 静态方法 调用 情况下 实例化      更新时间:2023-10-16

有没有办法在类模板中定义一个静态方法,然后可以在不指定实例化的情况下调用该方法?

我认为这在您有一些辅助静态函数的情况下可能很有用,该函数在逻辑上属于一个类(恰好是一个模板类(,但不依赖于模板参数。

我也不介意:

  1. 对所有具有相同的静态方法(包括地址和所有(实例化,或
  2. 每个实例化都有一个单独的静态方法,但能够在没有的情况下调用静态方法指定我调用方法的实例化(一些默认值将被调用(。

例如

template<typename T> class C {
public:
    static int func() { return 0; }
};
int main()
{
    // This works.
    return C<int>::func();   
    // These don't work.
    // return C<>::func();   
    // return C::func();   
}

最简单的解决方案可能是让静态函数属于基类,然后模板派生自基类:

struct CBase {
    static int func() { return 0; }
};
template<typename T> class C : public CBase {
public:
};
int main()
{
    // This works.
    return C<int>::func();
    // This will work too:
    return CBase::func();
}

您可以使用继承,这也将删除二进制文件中任何非静态函数(也不关心模板类型(的重复,即:

class A {
public:
    static int func() { return 0; }
};
template<typename T> 
class B : A {
};
<</div> div class="answers">

如果你想让CC<>工作,你可以依赖包含给定函数的基本非模板类,也可以使用模板专用化,如下所示:

template<typename...>
struct C;
template<>
struct C<> {
    static int func() { return 0; }
};
template<typename T>
struct C<T>: C<> {
    // all the other things around...
};
int main() {
    C<int>::func();   
    C<>::func();   
}

对于您不提供主模板的定义,接受的专用化包括:

  • 仅包含给定函数的C<>
  • 仅接受原始示例中的参数C<T>

在魔杖盒上看到它。


如果无法使用可变参数模板,仍可以使用自定义类型执行类似操作。
举个例子:

struct func_only {};
template<typename T = func_only>
struct C;
template<>
struct C<func_only> {
    static int func() { return 0; }
};
template<typename T>
struct C: C<func_only> {
    // all the other things around...
};
int main() {
    C<int>::func();   
    C<>::func();   
}

话虽如此,无论如何,使其成为免费功能在我看来是最好的解决方案。

这将如何工作?通常也依赖于静态函数中的类型。

template<typename T> class C {
public:
    static int func() { return sizeof(T); }
};

如果它们不依赖于它,您可能应该使它们成为自由函数,或此类基类的静态成员。