如何将模板类中的模板函数转换为功能指针
How to turn a template function in a template class to a function pointer
我正在尝试将混凝土工厂变成模板工厂类。以下是我写的;我正在使用G (GCC)4.8.5。
G 抱怨error: no matches converting function ‘create’ to type ‘using create_t = class Base* (*)() {aka class Base* (*)()}’
。句子create_t pf = create<S>;
失败了,但我不知道它是什么。
#include<iostream>
#include<type_traits>
class Base {
public:
virtual ~Base() {};
virtual void print() {
std::cout << "In Base." << std::endl;
}
};
class Derived: public Base {
public:
void print() {
std::cout << "In Derived." << std::endl;
}
};
template<typename T>
class Factory {
public:
using create_t = T* (*) ();
template<typename S>
T* create() {
static_assert(std::is_base_of<T, S>::value, "S must be a derived of T.");
return new S();
}
template<typename S>
void test() {
create_t pf = create<S>;
T * pt = pf();
pt->print();
delete pt;
}
};
int main() {
Factory<Base> base_factory;
base_factory.test<Derived>();
return 0;
}
您错过了static
关键字:
template<typename S>
static T* create() {
static_assert(std::is_base_of<T, S>::value, "S must be a derived of T.");
return new S();
}
演示
因为没有 static
,它是一个非静态成员函数,其类型为 T* (Factory::*) ();
如果您确实需要它作为非静态成员函数:
using self = Factory;
using create_t = T* (self::*) ();
template<typename S>
T* create() {
static_assert(std::is_base_of<T, S>::value, "S must be a derived of T.");
return new S();
}
template<typename S>
void test() {
create_t pf = &self::create<S>;
T * pt = (this->*pf)();
pt->print();
delete pt;
}
demo
相关文章:
- 转换指针引用的字符串
- 无法向上转换指针到指针参数
- 混合转换指针和引用
- 堆栈对象的强制转换指针
- 基类到派生模板类的强制转换指针,而不知道类型
- 删除类型转换指针的最佳方法
- 管理到本机值类转换:强制转换指针是否安全?
- 转换指针类型
- 为什么函数不能正确强制转换指针(从基类到派生类)
- 当我们递增下面的类型转换指针时会发生什么?
- 类型强制转换指针构造函数调用
- 如何转换(指针向量)-->(指向指针数组的指针)
- 如何从类功能转换指针
- 在C++对象中:我应该使用父类强制转换指针,还是应该使用实际类本身进行强制转换
- Delphi中的类型转换指针添加
- C++分段错误(核心转储)错误 - 强制转换指针/将函数值返回到线程
- 以C++和运算符优先级键入指向数组成员的强制转换指针
- C++动态强制转换指针的内存清理
- 转换指针和引用的好处
- 在c++中转换指针