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:
- Think about it—what if both
Product1andProduct2each had only one parameter? In that case,sizeofwould no longer be able to differentiate them. - 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
createProductfunction: ThecreateProductfunction now takes a template parameterTto specify the product type, eliminating the need for theProductTypeenum.- Removal of
switchstatement: Theswitchstatement is no longer needed as the compiler determines the correct type based on the template argument.- Explicit product type in
main: ThecreateProductfunction is called with explicit template arguments (Product1andProduct2) 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
ProductTypeenum 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 (
Product1,Product2, etc.) are derived from theProductbase class for this approach to work correctly.- Consider using
static_assertor concepts (if available in your C++ version) to enforce constraints on the template parameterT, 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;
}
