I have a class parametrized with a number, but only some values are in fact valid parameters. In order to hide implementation from user and to prevent invalid instantiating, I did this:
// foo.hpp
class IClass
{
virtual void doStuff() = 0;
};
IClass& getHiddenClass(const bool& randomCondition);
// foo.cpp
template <unsigned x>
class HiddenClass : public IClass
{
public:
void doStuff()
{
/* some code using x */
}
};
IClass& getHiddenClass(const bool& randomCondition)
{
static HiddenClass<42> ifRandomCondition;
static HiddenClass<9000> ifNotRandomCondition;
if (randomCondition)
return ifRandomCondition;
else
return ifNotRandomCondition;
}
Is it OK are is there a better workaround? This example is simplified and abstract, but I also won’t need to store a large number of valid instances.
Use
static_assertto prevent invalid instantiation, available in C++11.I don’t understand the purpose of your “hidden class”. Interfaces are meant to do exactly this – to hide the implementation from users and only let them have a predefined set of operations that they can use. Declare your interface in a separate header file and share it with user. Inherit your concrete class from the interface (in another, non-shared header file) and implement it in cpp file (again, non-shared).