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>
4
5 enum class ProductType {
6 Product1,
7 Product2
8 };
9
10 class Product {
11 public:
12 virtual ~Product() = default;
13 virtual void use() = 0;
14 };
15
16 // Concrete products with different arguments
17 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 };
24
25 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 };
33
34 // Singleton factory with modern techniques
35 class ProductFactory {
36 public:
37 static ProductFactory& getInstance() {
38 static ProductFactory instance;
39 return instance;
40 }
41
42 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 }
53
54 private:
55 ProductFactory() = default; // Private constructor for singleton
56 };
57
58 int main() {
59 ProductFactory& factory = ProductFactory::getInstance();
60
61 std::unique_ptr<Product> product1 = factory.createProduct(ProductType::Product1, 42);
62 std::unique_ptr<Product> product2 = factory.createProduct(ProductType::Product2, 5, "Hello");
63
64 product1->use();
65 product2->use();
66
67 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 Product2
return 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>
4
5 class Product {
6 public:
7 virtual ~Product() = default;
8 virtual void use() = 0;
9 };
10
11 // Concrete products with different arguments
12 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 };
19
20 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 };
28
29 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 singleton
46 };
47
48 int main() {
49 ProductFactory& factory = ProductFactory::getInstance();
50
51 std::unique_ptr<Product> product1 = factory.createProduct(42);
52 std::string hi("Hello");
53 std::unique_ptr<Product> product2 = factory.createProduct(5, hi);
54
55 product1->use();
56 product2->use();
57
58 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
Product1
andProduct2
each had only one parameter? In that case,sizeof
would 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
createProduct
function: ThecreateProduct
function now takes a template parameterT
to specify the product type, eliminating the need for theProductType
enum.- Removal of
switch
statement: Theswitch
statement is no longer needed as the compiler determines the correct type based on the template argument.- Explicit product type in
main
: ThecreateProduct
function is called with explicit template arguments (Product1
andProduct2
) 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 (
Product1
,Product2
, etc.) are derived from theProduct
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 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>::type
std::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;
}