Is a vtable created here ?
Yes since you have virtual
member functions.
Does it matter to me if a vtable is created or not, since I don't use it ?
Since you don't use it, it still matters in the sense that it will increase the size of your Derived
structure.
Here your Derived
structure is of size 8. But without the vtable, it would be of size 1.
Maybe there is another way to make sure the compiler complains if Derived
doesn't implement f()
?
To be honest, I think your solution using Base
as an interface in order to force every derived class to implement the f()
function is totally fine since it is the exact use-case for the use of interfaces.
But if the size of the Derived
structure is a concern (because you said you wanted to instantiate it millions of times), perhaps you would be interested by the std::is_member_function_pointer
type trait.
I have no idea about how you intend to instantiate your Derived
structure so I cannot provide a code that would exactly suit your needs.
But the idea I'm thinking about is equivalent to the following (generic example):
#include <type_traits>
template <typename T>
void instantiate_a_lot_of_times(std::size_t nb_times)
{
// Check if the f() member function exists
static_assert(std::is_member_function_pointer<decltype(&T::f)>::value, "Error: The T::f() member function must be defined");
for(std::size_t i = 0; i < nb_times; ++i)
{
T t;
// Do something with t
}
}
But keep in mind that this approach has the drawback of delaying the check.
The compilation will not fail when the structure definition is encountered but when the static_assert
is evaluated.