Home > Net >  How to pass generic arguments to the nested generic classes in C
How to pass generic arguments to the nested generic classes in C

Time:11-24

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?

CodePudding user response:

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.

CodePudding user response:

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?.

  • Related