在不指定实例化的情况下调用类模板的静态方法的方法
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 {
};
<</div>
div class="answers"> 如果你想让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>
在魔杖盒上看到它。
如果无法使用可变参数模板,仍可以使用自定义类型执行类似操作。
举个例子:
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); }
};
如果它们不依赖于它,您可能应该使它们成为自由函数,或此类基类的静态成员。
相关文章:
- 尝试了解在导入的静态方法上使用删除方法时的错误
- 如何通过命名空间调用非静态方法
- 如何在没有实例的情况下获取非静态方法的类型?
- 调用从模板派生的类的静态方法,而不指定模板
- 如何在 c++ 中异步调用静态方法?
- C++ 将静态方法转换为简单方法
- 从另一个标头中的标头调用静态方法
- C++中静态方法的局部变量范围
- 仅在少数方法(静态或共享库)中解析的外部符号
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 使用本机 JNI 静态方法实现C++ Java 运行时错误
- 当只有静态方法受到影响时,如何解决C++中的链接器错误?
- 静态变量在同一个翻译单元中被静态方法使用时是否保证被初始化?
- 为什么链接器报告全局函数的乘法定义符号,而不是类静态方法
- 从部分专用模板方法调用模板非静态方法
- 如何使用 c++ 在 cocos2dx 中定义非静态方法
- 使用 CMake 的静态方法链接错误
- 在子类上调用模板化静态方法时获取类的类型名
- 仅具有公共静态方法的帮助程序类
- 调用没有主体的未实现静态方法