从类模板的(部分)专门化调用静态函数
call static function of class template from its (partial) specialization
有没有办法让这些代码按预期工作?
#include <iostream>
using namespace std;
template<typename T> class templated{
public:
static void f(){
cout<<"doing something generically"<<endl;
}
};
template<> class templated<int>{
public:
static void g(){
cout<<"doing something else, but specific to int"<<endl;
f();
}
};
int main(){
templated<int>::g();
}
G++抱怨f没有在作用域中声明。我已经尝试了调用f()
的所有可能的变体(templated<int>::f()
,在templated
中放置一个伪声明,将声明移到类定义之外…),所有这些都失败了,所以我在这里省略它们。
在这种特殊情况下,您可以继承,因为您没有使用模板参数类型:
template<> class templated<int>: templated<void>{
public:
static void g(){
cout<<"doing something else, but specific to int"<<endl;
f();
}
};
不,专业化与基本模板完全分离,不会从中"继承"任何东西。
也许你可以添加一个可以从任何地方调用的免费函数?
您的专用版本根本没有f()
(这里没有"继承")。
如果您想要继承,您可能应该考虑将f()
移动到基类中。
您可以使用某种包装器,比如
template<typename T>
class templated_core
{
public:
static void f()
{
cout<<"doing something generically"<<endl;
}
};
template<typename T>
class templated : public templated_core<T>
{
};
template<>
class templated<int> : public templated_core<int>
{
public:
static void g()
{
cout<<"doing something else, but specific to int"<<endl;
f();
}
};
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 线程 std::调用未知类型,无法专门化函数错误
- 如何在c++运算符()中专门化调用模板
- 从专用模板方法调用无专门化的模板方法
- 从类模板的(部分)专门化调用静态函数
- 指针类型的类模板专门化调用中没有匹配的函数
- 基于运行时值调用不同的模板函数专门化
- 对STL算法进行专门化,以便在可用时自动调用高效的容器成员函数
- 根据调用方/上下文专门化函数的行为
- 专门化函数从其他函数调用
- 调用模板和专门化来交叉验证结果
- 如何在专门化版本中调用泛型模板函数
- C++模板专门化,对可以是指针或引用的类型调用方法
- 使用C调用约定调用函数模板专门化