c++通过模板实例化类

标签 c++

<分区>

有没有可能实现这样的目标?与其使用不同的函数来实例化不同的类,不如编写一个函数来实例化不同的类,如果它们从基类派生并采用相同的参数,那就太好了。

#include <iostream>
#include <string>
#include <vector>
#include <limits>

class Base
{
    void DoSomething()
    {
        std::cout << "Oh yes" << std::endl;
    }
};

class Derived1 : public Base
{

};

class Derived2 : public Base
{

};

template <typename T>
T* Create<T>()
{
    return new T;
}

int main()
{
    auto* test = Create<Derived1>();
    test->DoSomething();
    delete test;

    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    return 0;
}

最佳答案

你的

void DoSomething()

类成员函数是private默认情况下,如 vsoftco's comment 所述.制作 public可能会解决您的主要(语法)问题。


从语义上看:

不要使用 new/new[] , delete/delete[]请直接使用原始指针/c 风格的数组!除非你真的知道你需要它,并且你想要低级控制,否则它会使你的代码不必要地复杂化。

对于这样的Factory pattern ,我建议使用来自 c++ 标准动态内存管理工具的智能指针:

template <typename T>
std::unique_ptr<T> Create() {
    return std::unique_ptr<T>(new T());
    // Alternatively for c++14
    // return std::make_unique<T>(); 
}

上面是most simple variant ,其中工厂方法只是将所有权交给调用者。

一个真正的工厂可能会负责将更多的观察者或其他东西与创建的实例连接起来,你最终会需要一些 std::shared_ptr<T> / std::weak_ptr<T> 成语代替。


仔细查看您的代码,如下所示:

template <typename T>
T* Create() {
    return new T;
}

int foo() { 
    auto* test = Create<Derived1>();
    test->DoSomething();
    delete test; // what actually happens if Create<Derived1>() or
                 // test->DoSomething(); throws an exception? 
                 // Is the allocated memory tidied up?

    // Irrelevant:
    // std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    return 0;
}

int main() {
    int retcode = foo(); // Slightly deviated your sample
    // do something else ...
    return retcode;
}

关于c++通过模板实例化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30005485/

相关文章:

java - 从 Assets 加载 Android 中的着色器 - 最后有额外的符号?

c++ - 这个 C++ 语法到底叫什么?

c++ - 用assimp加载模型-不需要 boost 吗?

C++ 11/14/17 支持 "auto new"

c++ - Protobuf 版本冲突

c++ - 在函数、编译时或运行时创建的数组?

c++ - 为什么 C++17 引入 std::aligned_alloc?

C++,创建 vector 的 vector ?

c++ - ld : symbol(s) not found

c++ - 执行我的简单函数需要多少 CPU 周期?