How to call foo and bar ?

 struct A { struct B { template<typename T> int foo() { } }; template<typename T> struct C { int bar() { } }; }; int main() { A a; // ? } 
  • one
    But if in A there are no subobjects B and C - then for which objects to call foo and bar ? They are not static. - Harry

2 answers 2

You have no "subclasses" in the program.

Your program contains nested declarations of completely independent classes (and class templates). All that this style of declaration gives is a change in the naming of classes (nested templates / classes will be called A::B and A::C ) and the ability of nested classes to access private members of the enclosing class. Nothing else.

For the rest, these classes remain completely independent. You have an object of type A in the program, but there is no object of type A::B or A::C<> . Therefore it is impossible to call foo and bar - they simply have no one to call. Declare objects and call on health

 int main() { A::B b; b.foo<int>(); A::C<int> c; c.bar(); } 

As you can see, neither this nor A has anything to do with it. You might as well declare B and C outside of A Nothing would have changed except class names.

    You can also add functions in structure A that simply return these functions to nested structures:

     struct A { // ... template <typename T> int foo() { return B().foo<T>(); } template <typename T > int bar() { return C<T>().bar(); } }; 

    By calling these functions for object A , you basically call functions of nested structures:

     A a; a.bar<double>(); a.foo<double>();