0

I have a class and a nested class in C++ and they are both generic classes.

#define GENERIC template<typename T>
    
GENERIC
class Class1 final{
private:
    GENERIC
    class Class2 final{
    private:
        T class2Field{};
    };

    T class1Field{};
};

I want to pass the type parameter T that is passed to Class1 when instantiating it, all the way to the Class 2. How can I achieve that?

Jason
  • 36,170
  • 5
  • 26
  • 60
  • 3
    The first step is to _stop using macros_. – Passer By Nov 23 '22 at 12:43
  • 3
    By not using an idiosyncratic macro that creates your own *limited* C++ subset. Spell out the template introducer, and give each parameter its own name. Then you can use those names freely. This question is akin to the joke about the man going to the doctor and complaining "it hurts when I do this weird thing", so the doctor of course responds with "well then, don't do this weird thing". – StoryTeller - Unslander Monica Nov 23 '22 at 12:44
  • No need to use macro here. – Jason Nov 23 '22 at 12:47

2 Answers2

3

How to pass generic arguments to the nested generic classes in C++

Since the nested class is also templated, you can make use of default argument as shown below:

template<typename T>
class Class1 {
private:
//-----------vvvvvvvvvvvvvv---->use default argument
    template<typename U = T>
    class Class2 {
    private:
        U class2Field{};
    };

    T class1Field{};
};

Now Class1<int>::Class2::class2Field will be of type int.

Jason
  • 36,170
  • 5
  • 26
  • 60
2

Class2 can see the declaration of Class1, therefore will use Class1's T when not declared a templated class:

template<typename T>
class Class1 final {
private:
    class Class2 final {
    private:
        T class2Field{};
    };

    T class1Field{};
};

so Class1<int>::Class2::class2Field will be of type int.


If you want Class2 still to be a templated class, see this answer.


better not use macros: Why are preprocessor macros evil and what are the alternatives?.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
  • 1
    The question says that both class are generics. In your answer, nested class is not templated. – Jason Nov 23 '22 at 12:50
  • correct, I edited it. – Stack Danny Nov 23 '22 at 12:53
  • Instead of making your answer same as [mine](https://stackoverflow.com/a/74547125/12002570), you could've just added a link to my answer saying something like if `Class2` is also a template then refer to that answer. – Jason Nov 23 '22 at 12:55
  • I edited before you posted, I can rollback, sure. – Stack Danny Nov 23 '22 at 12:56
  • Our answer can be complementary to each other. That way there will be no conflict as technically my answer was posted slightly before your edit for the same. Both answer can be helpful to the OP. – Jason Nov 23 '22 at 12:57