C++:如何为运行时模板参数创建对象工厂?

标签 c++ templates runtime

我想创建一个整数映射到模板类的对象。模板参数是一个整数,模板参数的值在编译时未知

我看过这个问题:C++: Passing a variable as a template argument它有帮助,但我还是有点卡住了。我试图避免使用 switch/case 语句;我不想写很多 case

我下面的例子没有编译,但它捕获了我想要做的事情的实质。有人可以帮我完成这个吗?

#include <iostream>
#include <map>

class File{
    public:
        File(int MF): mf(MF) {  }
        int mf;
};

template <int MF>
class tFile: public File{
    public:
        tFile(): File(MF){   }
        void print() { std::cout << "MF=" << MF << std::endl;}
};

File* createMF0(){
    return new tFile<0>;
}
File* createMF1(){
    return new tFile<1>;
}
File* createMF2(){
    return new tFile<2>;
}
File* createMF3(){
    return new tFile<3>;
}

int main(){

    std::cout << "\nI'm learning about templates." << std::endl;

    File myFile(3);
    std::cout << "\nmyFile  has MF=" << myFile.mf << std::endl;

    tFile<4> myTFile;
    std::cout << "myTFile has ";
    myTFile.print();

    // Now for the real stuff
    std::map<int, std::function<File*>> createMF;
    std::map<int, File*> templateFiles;

    createMF[0] = createMF0;
    createMF[1] = createMF1;
    createMF[2] = createMF2;
    createMF[3] = createMF3;

    // Here I'm trying to avoid a switch statement
    std::cout << std::endl;
    for (int i=0; i <= 3; i++){
        std::cout << "i = " << i << std::endl;
        templateFiles[i] = createMF[i]();
    }

    return 0;
}

最佳答案

换行

std::map<int, std::function<File*>> createMF;

std::map<int, std::function<File*()>> createMF;

实例化 std::functional 的模板参数类型不是 File* 而是一个没有参数并返回 File* 的函数

更新

您可以使用另一个模板稍微简化您的代码。而不是

File* createMF0(){
    return new tFile<0>;
}
File* createMF1(){
    return new tFile<1>;
}
File* createMF2(){
    return new tFile<2>;
}
File* createMF3(){
    return new tFile<3>;
}

你可以只有一个功能:

template <int N>
File* createMF(){
    return new tFile<N>;
}

如果这样做,main 函数的核心需要更改为:

// Now for the real stuff
std::map<int, std::function<File*()>> createFunctions;
std::map<int, File*> templateFiles;

createFunctions[0] = createMF<0>;
createFunctions[1] = createMF<1>;
createFunctions[2] = createMF<2>;
createFunctions[3] = createMF<3>;

// Here I'm trying to avoid a switch statement
std::cout << std::endl;
for (int i=0; i <= 3; i++){
    std::cout << "i = " << i << std::endl;
    templateFiles[i] = createFunctions[i]();
}

关于C++:如何为运行时模板参数创建对象工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23354823/

相关文章:

适用于 Mac 和 Win 的 C++ 跨平台 UI 框架?

c++ - 使用模板化成员函数指针作为模板参数

javascript - ng-repeat 和 ng-class 的 Angular 模板指令

c++ - CRTP 静态多态性 : Using the Base Class to Call Derived Methods

c - 代码没有输出,但正在运行。 [C]

c++ - 为什么 unsigned char 用于 RGB 像素数据?

c++ - 通过引用调用 : Use of undeclared identifier

c++ - 测试用例的意外输出

c++ - 由于从未运行的函数调用,程序花费的时间比应有的时间长很多

c++ - C/C++ : How to check if an array is static or dynamic during runtime