繁体   English   中英

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

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

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

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

我也不介意:

  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 {

};

如果要使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>仅接受原始示例中的参数

wandbox上看到它。


如果您不能使用可变参数模板,则仍可以对自定义类型执行类似的操作。
举个例子:

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); }
};

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM