如何将模板类中的模板函数转换为函数指针

时间:2016-12-01 08:48:42

标签: c++ templates

我正在尝试将具体工厂变成模板工厂类。以下是我写的内容;我正在使用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;
}

1 个答案:

答案 0 :(得分:2)

您错过了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();
} 

Demo

因为没有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