I know that it isn't possible to have class methods that are both pure virtual and static (see this discussion). So, I ask: is there a way to guarantee that a bunch of derived classes have static functions that do the same thing and that are guaranteed to be named in the same way?
Consider the following example:
#include <iostream>
#include <array>
// class base {
// public:
// virtual static constexpr size_t nums() = 0
// }
template<size_t num>
class derived1 {//: public base {
public:
static constexpr size_t nums() {return num;}
derived1() {}
};
template<size_t num>
class derived2 {// : public base {
public:
static constexpr size_t nums() {return num;}
derived2() {}
};
int main() {
std::cout << derived2<20>::nums() << "\n";
return 0;
}
I commented out the base class so that it compiles, but I want an interface class that guarantees a bunch of derived classes all have nums() named in the same way. In this particular example nums is named the same way in both derived class, but if I write a third derived class a few years from now, and I forget this convention, I don't want to be able to compile anything, ideally.
You could use CRTP as the base class, and then have a routine that depends on the derived class having implemented the expected static function.
Here's an example, and I have thunk_nums in the base class dependent on the derived class having nums, although they could have been named the same.
Note that if a function isn't used, it won't be generated, and so won't trigger an error. (Which may be desired behavior, or if not desired then steps would have to be taken to ensure it is generated.)
#include <iostream>
template <typename DERIVED>
class base {
public:
static constexpr size_t thunk_nums() {
return DERIVED::nums();
}
};
template<size_t num>
class derived1 : public base<derived1<num>> {
public:
static constexpr size_t nums() {return num;}
derived1() {}
};
template<size_t num>
class derived2 : public base<derived2<num>> {
public:
static constexpr size_t nums() {return num;}
derived2() {}
};
int main() {
std::cout << derived2<20>::thunk_nums() << "\n";
}
What is the best way to create an array of objects derived from an abstract template base class without violating the strict-aliasing rule. Each derived object will define the template arguments of the base class differently but only through the constant enum value. Here is an example
enum BlaEnum
{
Bla1,
Bla2,
Bla3
};
template <class T, BlaEnum bla = Bla1>
class A
{
public:
virtual void Foo() = 0;
T att;
BlaEnum bll;
};
class B : public A<int, BlaEnum::Bla2>
{
public:
void Foo() override;
};
class C : public A<int, BlaEnum::Bla3>
{
public:
void Foo() override;
};
int main(void)
{
B b;
C c;
//violates strict-aliasing rule
A<int>* BaseArr[2] = { (A<int>*)&b,(A<int>*)&c };
}
The problem here is that class B : public A<int, BlaEnum::Bla2> and class C : public A<int, BlaEnum::Bla3> derive from different A that are not compatible with each other. Each of those classes causes the instantiation of a new template class (neither of which are compatible with A<int>).
In order to have valid common base you require a base class that does not differ in any template parameters (or is a non-template class) from the derived classes.
Modifying your example e.g.:
template <class T>
class Base
{
public:
virtual void Foo() = 0;
};
template <class T, BlaEnum bla = Bla1>
class A : public Base<T>
{
public:
T att;
BlaEnum bll;
};
// B and C are unchanged
int main()
{
B b;
C c;
// Array of pointers to common base class
Base<int>* BaseArr[2] = { &b,&c };
}
One more note: C-style arrays are not a good practice, you should prefer std::array(or std::vector) and smart pointer over raw pointers
The code below won't compile:
struct Base
{
std::vector<void(Base::*)(void)> x;
};
struct Derived : public Base
{
void foo() {}
};
// ...
Derived d;
d.x.push_back(&Derived::foo);
Is it possible to refer derived class in template member x? In the example above I specify exactly Base and derived classes cannot push their own member functions into vector x.
Casting is bad since your code have to assume that this will be called only for instance of Derived class. This means that you either have to assume that all items in x are instance of Derived (in such case declaration of x is to general and should be changed to std::vector<void(Derived::*)(void)> x;) or you have to maintain extra information what which class method is stored in specific position of x. Both approaches are bad.
In modern C++ it is much better do do it like this:
struct Base
{
std::vector<std::function<void()>> x;
};
struct Derived : public Base
{
void foo() {}
};
// ...
Derived d;
d.x.push_back([&d](){ d.foo(); });
Another good approach can be CRTP:
template<class T>
struct Base
{
std::vector<void(T::*)(void)> x;
};
struct Derived : public Base<Derived>
{
void foo() {}
};
// ...
Derived d;
d.x.push_back(&Derived::foo);
You may, but there is no implicit conversion; it requires a cast.
Derived d;
d.x.push_back(static_cast<void(Base::*)()>(&Derived::foo));
The caveat is the if you use that pointer to member with an object that isn't really a Derived, the behavior is undefined. Tread carefully.
As an addendum, if you want to get rid of the cast when taking the pointer, you can do that by encapsulating the push (with some static type checking to boot):
struct Base
{
std::vector<void(Base::*)(void)> x;
template<class D>
auto push_member(void (D::* p)()) ->
std::enable_if_t<std::is_base_of<Base, D>::value> {
x.push_back(static_cast<void(Base::*)()>(p));
}
};
I think I would express this by calling through a non-virtual member function on the base.
example:
#include <vector>
struct Base
{
std::vector<void(Base::*)(void)> x;
// public non-virtual interface
void perform_foo()
{
foo();
}
private:
// private virtual interface for the implementation
virtual void foo() = 0;
};
struct Derived : public Base
{
private:
// override private virtual interface
void foo() override {}
};
// ...
int main()
{
Derived d;
d.x.push_back(&Base::perform_foo);
auto call_them = [](Base& b)
{
for (auto&& item : b.x)
{
(b.*item)();
}
};
call_them(d);
}
In C++11 Is there some way I can define a static member variable in a subclass that is accessed by the (abstract) base class constructor? I've unsuccessfully tried messing with initialization lists, and tried setting a non-static base class pointer to that static subclass member. I'm starting to think I'll have to write a separate constructor for each subclass just so I can do this. Any ideas?
You can pass the subclass type to the base class as a template argument:
#include <iostream>
template <typename Derived>
struct Base
{
Base()
{
std::cout << Derived::value << std::endl;
}
};
struct Foo : Base<Foo>
{
static const std::size_t value = 100;
};
struct Bar : Base<Bar>
{
static const std::size_t value = 999;
};
int main()
{
Foo baseFoo;
Bar baseBar;
}
live example
I am trying to use template meta-programming to determine the base class. Is there a way to get the base class automatically without explicitly specializing for each derived class?
class foo { public: char * Name() { return "foo"; }; };
class bar : public foo { public: char * Name() { return "bar"; }; };
template< typename T > struct ClassInfo { typedef T Base; };
template<> struct ClassInfo<bar> { typedef foo Base; };
int main()
{
ClassInfo<foo>::Base A;
ClassInfo<bar>::Base B;
std::cout << A.Name(); //foo
std::cout << B.Name(); //foo
}
for right now any automatic method would need to select the first declared base and would fail for private bases.
It's possible with C++11 and decltype. For that, we'll exploit that a pointer-to-member is not a pointer into the derived class when the member is inherited from a base class.
For example:
struct base{
void f(){}
};
struct derived : base{};
The type of &derived::f will be void (base::*)(), not void (derived::*)(). This was already true in C++03, but it was impossible to get the base class type without actually specifying it. With decltype, it's easy and only needs this little function:
// unimplemented to make sure it's only used
// in unevaluated contexts (sizeof, decltype, alignof)
template<class T, class U>
T base_of(U T::*);
Usage:
#include <iostream>
// unimplemented to make sure it's only used
// in unevaluated contexts (sizeof, decltype, alignof)
template<class T, class R>
T base_of(R T::*);
struct base{
void f(){}
void name(){ std::cout << "base::name()\n"; }
};
struct derived : base{
void name(){ std::cout << "derived::name()\n"; }
};
struct not_deducible : base{
void f(){}
void name(){ std::cout << "not_deducible::name()\n"; }
};
int main(){
decltype(base_of(&derived::f)) a;
decltype(base_of(&base::f)) b;
decltype(base_of(¬_deducible::f)) c;
a.name();
b.name();
c.name();
}
Output:
base::name()
base::name()
not_deducible::name()
As the last example shows, you need to use a member that is actually an inherited member of the base class you're interested in.
There are more flaws, however: The member must also be unambiguously identify a base class member:
struct base2{ void f(){} };
struct not_deducible2 : base, base2{};
int main(){
decltype(base_of(¬_deducible2::f)) x; // error: 'f' is ambiguous
}
That's the best you can get though, without compiler support.
My solutions are not really automatic, but the best I can think of.
Intrusive C++03 solution:
class B {};
class A : public B
{
public:
typedef B Base;
};
Non-intrusive C++03 solution:
class B {};
class A : public B {};
template<class T>
struct TypeInfo;
template<>
struct TypeInfo<A>
{
typedef B Base;
};
I am not aware of any base-class-selecting template, and I'm not sure one exists or is even a good idea. There are many ways in which this breaks extensibility and goes against the spirit of inheritance. When bar publicly inherits foo, bar is a foo for all practical purposes, and client code shouldn't need to distinguish base class and derived class.
A public typedef in the base class often scratches the itches you might need to have scratched and is clearer:
class foo { public: typedef foo name_making_type; ... };
int main() {
Foo::name_making_type a;
Bar::name_making_type b;
}
What's with the base class? Are you a .NET or Java programmer?
C++ supports multiple inheritance, and also does not have a global common base class. So a C++ type may have zero, one, or many base classes. Use of the definite article is therefore contraindicated.
Since the base class makes no sense, there's no way to find it.
I am looking for a portable resolution for similar problems for months. But I don't find it yet.
G++ has __bases and __direct_bases. You can wrap them in a type list and then access any one of its elements, e.g. a std::tuple with std::tuple_element. See libstdc++'s <tr2/type_traits> for usage.
However, this is not portable. Clang++ currently has no such intrinsics.
With C++11, you can create a intrusive method to always have a base_t member, when your class only inherits from one parent:
template<class base_type>
struct labeled_base : public base_type
{
using base_t = base_type; // The original parent type
using base::base; // Inherit constructors
protected:
using base = labeled_base; // The real parent type
};
struct A { virtual void f() {} };
struct my_class : labeled_base<A>
{
my_class() : parent_t(required_params) {}
void f() override
{
// do_something_prefix();
base_t::f();
// do_something_postfix();
}
};
With that class, you will always have a parent_t alias, to call the parent constructors as if it were the base constructors with a (probably) shorter name, and a base_t alias, to make your class non-aware of the base class type name if it's long or heavily templated.
The parent_t alias is protected to don't expose it to the public. If you don't want the base_t alias is public, you can always inherit labeled_base as protected or private, no need of changing the labeled_base class definition.
That base should have 0 runtime or space overhead since its methods are inline, do nothing, and has no own attributes.
Recently when I reading Unreal Engine source code, I found a piece of code meet your requirement.
Simplified code is below:
#include <iostream>
#include <type_traits>
template<typename T>
struct TGetBaseTypeHelper
{
template<typename InternalType> static typename InternalType::DerivedType Test(const typename InternalType::DerivedType*);
template<typename InternalType> static void Test(...);
using Type = decltype(Test<T>(nullptr));
};
struct Base
{
using DerivedType = Base;
static void Print()
{
std::cout << "Base Logger" << std::endl;
}
};
struct Derived1 : Base
{
using BaseType = typename TGetBaseTypeHelper<Derived1>::Type;
using DerivedType = Derived1;
static void Print()
{
std::cout << "Derived1 Logger" << std::endl;
}
};
struct Derived2 : Derived1
{
using BaseType = typename TGetBaseTypeHelper<Derived2>::Type;
using DerivedType = Derived2;
static void Print()
{
std::cout << "Derived2 Logger" << std::endl;
}
};
int main()
{
Derived1::BaseType::Print();
Derived2::BaseType::Print();
}
Using a macro below to wrap those code make it simple:
#define DECLARE_BASE(T) \
public: \
using BaseType = typename TGetBaseTypeHelper<T>::Type; \
using DerivedType = T;
I got confused when first seeing these code. After I read #Xeo 's answer and #juanchopanza 's answer, I got the point.
Here's the keypoint why it works:
The decltype expression is part of the member declaration, which does
not have access to data members or member functions declared after
it.
For example:
In the declaration of class Derived1, when declaring Derived1::BaseType, Derived1::BaseType doesn't know the existence of Derived1::DerivedType. Because Derived1::BaseType is declared before Derived1::DerivedType. So the value of Derived1::BaseType is Base not Derived1.