Introduction
One of the most powerful language features that we get with C++17 is the compile-time if in the form of `if constexpr`. It allows you to check, at compile time, a condition and depending on the result the code is rejected from the further steps of the compilation. In this chapter, you’ll see one example of how this new feature can simplify the code.
We'll cover the following...
The Problem
In item 18 of Effective Modern C++ Scott Meyers described a method called makeInvestment
:
Press + to interact
template<typename... Ts>std::unique_ptr<Investment>makeInvestment(Ts&&... params);
There’s a factory method that creates derived classes of Investment
, and the main advantage is
that it supports a variable number of arguments!
For example, here are the proposed derived types:
Press + to interact
// base type:class Investment{public:virtual ~Investment() { }virtual void calcRisk() = 0;};class Stock : public Investment{public:explicit Stock(const std::string&) { }void calcRisk() override { }};class Bond : public Investment{public:explicit Bond(const std::string&, const std::string&, int) { }void calcRisk() override { }};class RealEstate : public Investment{public:explicit RealEstate(const std::string&, double, int) { }void calcRisk() override { }};
The code from the book was too idealistic, and it worked until ...