欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > Collaborate with AI -- Write a modern C++ singleton factory

Collaborate with AI -- Write a modern C++ singleton factory

2025/2/24 16:47:26 来源:https://blog.csdn.net/zhaiminlove/article/details/145017496  浏览:    关键词:Collaborate with AI -- Write a modern C++ singleton factory

translate  my blog <<与AI合作 -- 写一个modern c++单例工厂>> to English.

=========================================================================

NOTE: It was written at 2024.01, maybe the AI is not smart as now.

Preface


In this article, readers can learn about a hybrid of the modern C++ singleton pattern and factory pattern. At the same time, you will gain insights into:

  • How intelligent AI has become today,
  • How to leverage AI to quickly turn ideas into reality, and
  • Whether such a level of intelligence might make programmers lose their jobs?

Question
This time, I won't use ChatGPT; instead, I've switched to Bard.

mzhai: Write a Modern c++ program to implement a singleton factory to produce 2 products. Each product has different arguments, the 1st has only one parameter of type int, the 2nd product has two parameters int and string respectively.

 Here, I specifically requested creating two products with different parameters to ensure that the classes generated by AI are versatile.

The answer given by bard

  1 #include <iostream>2 #include <memory>3 #include <utility>45 enum class ProductType {6     Product1,7     Product28 };910 class Product {11 public:12     virtual ~Product() = default;13     virtual void use() = 0;14 };1516 // Concrete products with different arguments17 class Product1 : public Product {18 public:19     Product1(int arg1) : arg1_(arg1) {}20     void use() override { std::cout << "Using Product1 with arg1: " << arg1_ << std::endl; }21 private:22     int arg1_;23 };2425 class Product2 : public Product {26 public:27     Product2(int arg2_1, std::string arg2_2) : arg2_1_(arg2_1), arg2_2_(arg2_2) {}28     void use() override { std::cout << "Using Product2 with arg2_1: " << arg2_1_ << ", arg2_2: " << arg2_2_ << std::endl;     }29 private:30     int arg2_1_;31     std::string arg2_2_;32 };3334 // Singleton factory with modern techniques35 class ProductFactory {36 public:37     static ProductFactory& getInstance() {38         static ProductFactory instance;39         return instance;40     }4142     template <typename... Args>43     std::unique_ptr<Product> createProduct(ProductType type, Args&&... args) {44         switch (type) {45             case ProductType::Product1:46                 return std::make_unique<Product1>(std::forward<Args>(args)...);47             case ProductType::Product2:48                 return std::make_unique<Product2>(std::forward<Args>(args)...);49             default:50                 throw std::invalid_argument("Invalid product type");51         }52     }5354 private:55     ProductFactory() = default; // Private constructor for singleton56 };5758 int main() {59     ProductFactory& factory = ProductFactory::getInstance();6061     std::unique_ptr<Product> product1 = factory.createProduct(ProductType::Product1, 42);62     std::unique_ptr<Product> product2 = factory.createProduct(ProductType::Product2, 5, "Hello");6364     product1->use();65     product2->use();6667     return 0;68 }

The problem with AI's answers

It fails with compilation errors, the error message is listed as below:

/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/12/bits/unique_ptr.h:1065:34: error: no matching constructor for initialization of 'Product2'
 1065 |     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
      |                                  ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/insights/insights.cpp:48:29: note: in instantiation of function template specialization 'std::make_unique<Product2, int>' requested here
   48 |                 return std::make_unique<Product2>(std::forward<Args>(args)...);
      |                             ^

It’s a bit strange, right? On line 62, we clearly passed two parameters to Product2. Doesn’t it only go to case ProductType::Product2 (line 48) when Product2 is involved? However, the compiler complains that only one int was passed to the constructor of Product2. Why?

This is because case statements are runtime code, while createProduct generates two overloads respectively based on lines 61 and 62, each containing all the code of createProduct body. For example, line 61 would generate the following code:

std::unique_ptr<Product> createProduct(ProductType type, int arg) {switch (type) {case ProductType::Product1:return std::make_unique<Product1>(arg);case ProductType::Product2:return std::make_unique<Product2>(arg);default:throw std::invalid_argument("Invalid product type");}
}

The generated code std::make_unique<Product2>(arg) doesn't match the unique one constructor Product2(int arg2_1, std::string arg2_2) .

Ask Bard to make improvement

Directly pasting the error to Bard, it still failed to truly understand the reason for the compilation error. The reason I say this is the solution it provided was:

case ProductType::Product2:if constexpr (sizeof...(Args) == 2) { // Ensure 2 arguments for Product2return std::make_unique<Product2>(std::forward<Args>(args)...);} else {throw std::invalid_argument("Invalid arguments for Product2");}

constexpr (sizeof...(Args) == 2) does indeed evaluate to TRUE/FALSE at compile time: if the condition is not met, this piece of code will be skipped. As a result, the createProduct function instantiated on line 61 will not produce any error. Let’s try this approach for now, even though it is ugly(which will be discussed later). 

  1 #include <iostream>2 #include <memory>3 #include <utility>45 class Product {6 public:7     virtual ~Product() = default;8     virtual void use() = 0;9 };1011 // Concrete products with different arguments12 class Product1 : public Product {13 public:14     Product1(int arg1) : arg1_(arg1) {}15     void use() override { std::cout << "Using Product1 with arg1: " << arg1_ << std::endl; }16 private:17     int arg1_;18 };1920 class Product2 : public Product {21 public:22     Product2(int arg2_1, std::string arg2_2) : arg2_1_(arg2_1), arg2_2_(arg2_2) {}23     void use() override { std::cout << "Using Product2 with arg2_1: " << arg2_1_ << ", arg2_2: " << arg2_2_ << std::endl;     }24 private:25     int arg2_1_;26     std::string arg2_2_;27 };2829 class ProductFactory {30 public:31     static ProductFactory& getInstance() {32         static ProductFactory instance;33         return instance;34     }35     template <typename... Args>36     std::unique_ptr<Product> createProduct(Args&&... args) {37         if constexpr (sizeof...(Args) == 1){38             return std::make_unique<Product1>(std::forward<Args>(args)...);39         }40         if constexpr (sizeof...(Args) == 2){41             return std::make_unique<Product2>(std::forward<Args>(args)...);42         }43     }44 private:45     ProductFactory() = default; // Private constructor for singleton46 };4748 int main() {49     ProductFactory& factory = ProductFactory::getInstance();5051     std::unique_ptr<Product> product1 = factory.createProduct(42);52     std::string hi("Hello");53     std::unique_ptr<Product> product2 = factory.createProduct(5, hi);5455     product1->use();56     product2->use();5758     return 0;59 }

Compile and run, both no problem. Moreover, let's dig deeply a little bit by cppinsights.io to look at the two instatiated functions:

 Obviously, this approach is not ideal:

  1. Think about it—what if both Product1 and Product2 each had only one parameter? In that case, sizeof would no longer be able to differentiate them.
  2. Moreover, this method generates a lot of redundant code (if constexpr...).

Back to human being

So, let me quickly fix it myself. We can pass an additional template parameter to the createProduct function, for example, called T, like this:

template <typename T, typename... Args>
std::unique_ptr<T> createProduct(Args&&... args) {return std::make_unique<T>(std::forward<Args>(args)...);
}...std::unique_ptr<Product> product1 = factory.createProduct<Product1>(42);
std::string hi("Hello");
std::unique_ptr<Product> product2 = factory.createProduct<Product2>(5, hi);

Let's look at how createProduct being instantiated.

 Ask Bard how about this improvement? It says:

mzhai:How about changing the code to above?

Bard: I'm happy to review the proposed code changes:

Key Changes:

  • Templated createProduct function: The createProduct function now takes a template parameter T to specify the product type, eliminating the need for the ProductType enum. 
  • Removal of switch statement: The switch statement is no longer needed as the compiler determines the correct type based on the template argument.
  • Explicit product type in main: The createProduct function is called with explicit template arguments (Product1 and Product2) to create the desired product types.

Analysis:

  • Pros:
    • More concise and less verbose code. 
    • Leverages template metaprogramming for type-driven behavior.
    • Potentially easier to extend for new product types.
  • Cons:
    • Might be less readable for those less familiar with templates.
    • Error messages might be more cryptic due to template instantiation.
    • Doesn't enforce a closed set of product types (could potentially create other types).

Overall:

  • The changes are valid and adhere to modern C++ practices.
  • The choice between this approach and the previous one using the ProductType enum is mainly a matter of preference and trade-offs.
  • Consider the team's familiarity with templates and the specific project requirements when deciding on the best approach.

Additional Notes:

  • Ensure that all product classes (Product1Product2, etc.) are derived from the Product base class for this approach to work correctly.
  • Consider using static_assert or concepts (if available in your C++ version) to enforce constraints on the template parameter T, ensuring it's a valid product type.

AI VS Human being

AI is indeed still limited in intelligence, but it can undeniably improve programming efficiency. Tools like Copilot are often advertised as being able to boost human programming efficiency by around 50%. Does this mean that, without new job opportunities being created, half of the engineers will lose their jobs?

Final code

You can copy below code and do expeirments.

#include <iostream>
#include <memory>
#include <utility>class Product {
public:virtual ~Product() = default;virtual void use() = 0;
};// Concrete products with different arguments
class Product1 : public Product {
public:Product1(int arg1) : arg1_(arg1) {}void use() override { std::cout << "Using Product1 with arg1: " << arg1_ << std::endl; }
private:int arg1_;
};class Product2 : public Product {
public:Product2(int arg2_1, std::string arg2_2) : arg2_1_(arg2_1), arg2_2_(arg2_2) {}void use() override { std::cout << "Using Product2 with arg2_1: " << arg2_1_ << ", arg2_2: " << arg2_2_ << std::endl; }
private:int arg2_1_;std::string arg2_2_;
};class ProductFactory {
public:static ProductFactory& getInstance() {static ProductFactory instance;return instance;}template <typename T, typename... Args>//typename std::enable_if<std::is_same<Product,T>::value, void>::typestd::unique_ptr<T> createProduct(Args&&... args) {return std::make_unique<T>(std::forward<Args>(args)...);}private:ProductFactory() = default; // Private constructor for singleton
};int main() {ProductFactory factory;std::unique_ptr<Product> product1 = factory.createProduct<Product1>(42);std::string hi("Hello");std::unique_ptr<Product> product2 = factory.createProduct<Product2>(5, hi);product1->use();product2->use();return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词