Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

c++ 编写一个模板函数,为类型T new一个新的对象

  1. User

    c++ 编写一个模板函数,为类型T new一个新的对象

  2. Assistant

    以下是一个示例实现:

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

    使用方式如下:

    // 创建一个 int 类型的对象
    int* ip = create<int>();
    // 创建一个 string 类型的对象
    string* sp = create<string>();
    

    该模板函数可以为任何类型创建一个新的对象,并返回一个指向该对象的指针。注意,在使用完毕后,需要手动释放内存以避免内存泄漏。例如:

    delete ip;
    delete sp;
    
  3. User

    c++宏定义能否通过判断参数类型,生成不同代码

  4. Assistant

    宏定义可以通过 sizeof 操作符判断参数类型的大小,从而生成不同的代码。以下是一个示例:

    #define CREATE(type) \
        do { \
            type* p = nullptr; \
            if (sizeof(type) == sizeof(int)) { \
                p = new int(); \
            } else if (sizeof(type) == sizeof(double)) { \
                p = new double(); \
            } else if (sizeof(type) == sizeof(char)) { \
                p = new char(); \
            } else { \
                static_assert(false, "unsupported type"); \
            } \
            // do something with p... \
        } while(false)
    

    使用方式如下:

    CREATE(int);       // 生成一个 int 类型的对象
    CREATE(double);    // 生成一个 double 类型的对象
    CREATE(char);      // 生成一个 char 类型的对象
    

    在上面的宏定义中,使用了 static_assert 函数来检查传入的类型是否受支持。如果传入的类型不是 int、double 或 char,将会抛出编译时错误,提示参数类型不受支持。