![](/img/trans.png)
[英]Call a static method of a class derived from template without specifying template
[英]Way to call a static method of a class template without specifying an instantiation?
有什么方法可以在类模板中定义静态方法,然后在不指定实例化的情况下调用该方法?
我认为这在您有一些辅助静态函数的情况下很有用,该函数在逻辑上属于一个类(恰好是模板类),但不依赖于模板参数。
我也不介意:
例如
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 {
};
如果要使C
或C<>
正常工作,则可以依赖包含给定函数的基本非模板类,也可以使用模板专门化,如下所示:
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.