Non-type type parameter, the type of which depends on another parameter

I am trying to define a template function that has a type parameter and a non-type parameter. However, the type of a non-type parameter depends on the type parameter. It looks like this:

template<typename T>
class A{
    typedef T* Pointer;
};

template<typename T, A<typename T>::Pointer P>
T fun(){
    return *P;
}

int main(){
    fun<int, (int*)0>();
}

If I compile the code, the compiler complains:

test.cpp:6:34: error: template argument 1 is invalid
 template<typename T, A<typename T>::Pointer P>
                                  ^
test.cpp:6:45: error: expected ‘>’ beforePtemplate<typename T, A<typename T>::Pointer P>
                                             ^

What should I do to make my code work? Thank!

PS. The above code is just an example of a structure. I know that the code itself does not make sense.

0
source share
2 answers

You almost put it typenamein the right place.

template<typename T, typename A<T>::Pointer P>

In addition, it Pointer typedefmust be publicly available for this to work.

+3
source

It works when you correct the syntax and access control:

template<typename T>
class A
{
public:                                            // must be accessible!
    typedef T* Pointer;
};

template<typename T, typename A<T>::Pointer P>     // like this
T fun()
{
    return *P;
}

int main()
{
    fun<int, (int*)0>();
}
+4
source

Source: https://habr.com/ru/post/1696289/


All Articles