I have a problem when I declare template class inside another a template class.

#pragma once
template<typename T>
class D<T>;//error 1,2
template<typename T>
class B
{
	D* d;
public:
	B(void){
    
	}
	~B(void){

	}
};
#pragma once
#include<iostream>
using namespace std;
template<typename T>
class B<T>;// error 3
template<typename T>
class D
{
	B* b;
public:
	D(void){
     
	}
	~D(void){

	}
};

the error message is

Error 1 error C2143: syntax error : missing ';' before '<'
Error 2 error C2059: syntax error : '<'
Error 3 error C2753: 'B<T>' : partial specialization cannot match argument list for primary template

any help will be appreciated.

Recommended Answers

All 4 Replies

Take the <T> part out of your forward declarations. You're just declaring a templated name, not instantiating it. Technically, you could do this since the template parameter name isn't used:

// Forward declare Foo<>
template <typename>
class Foo;

Does this second template happen to be the same as the first one? I mean the same type.
You could try to delete that code if that's the case. If its not, change T for another letter, like U.

Oh, he's solution is better. Stick with it =D.
But check if you really need a template inside a templated class.

If you need to instantiate them, there must be a way of declarating 2 templates at once, like <template T, template U>. I don't know. Im a little new to C++.

Of course, follow Narue's advice, she's always right! But, just to add to it:

You will have to specify the type for the use of the class template in your other class template:

#pragma once
template<typename T>
class D; //remove the <T>

template<typename T>
class B
{
	D<T>* d; //but you need it here. Or, at least, you need something between <>.
public:
	B(void){
    
	}
	~B(void){

	}
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.