james
james

Reputation: 262

non-type template parameter whose type depends on another parameter

I'm trying to define a template function who has a type parameter and a non-type parameter. However, the type of the non-type parameter depends on the type parameter. It looks like the following:

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 ‘>’ before ‘P’
 template<typename T, A<typename T>::Pointer P>
                                             ^

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

PS. The above code is just a example of the structure. I know the code itself is meaningless.

Upvotes: 1

Views: 1277

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477600

It works when you fix the syntax and the 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>();
}

Upvotes: 5

Brian Bi
Brian Bi

Reputation: 119572

You almost put the typename in the right place.

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

Also, the Pointer typedef needs to be public in order for this to work.

Upvotes: 5

Related Questions