Unique_ptr with templates

Goodmorning to everyone.
I'm trying to use smart_pointers for representing template variables into classes.

Here an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <memory>

using namespace std;

template <typename T> struct structure {
	int i;
	char c;
	T t;
};

template <typename T> class test {
public:
	test();
	void function();
private:
	unique_ptr<structure<T>> ptr;
};

template <typename T> test<T>::test() {
	ptr.reset(new structure<T>);
}

template<typename T> void prova<T>::function() {
	ptr->i = 0;
	cout << ptr->i;
}


the code that you see there works, but into function() ptr->i is not recognise from the compiler, in fact the compiler see "i" as unknown when i point it with ptr->i. And if i should need a string into the structure i couldn't use all the string function associated to it like size() because it is see as unknown.

On the other hand when i realise this code without templates all works correctly, so where am i wrong?

Thanks to all will give me some advice!

Side note: I'm working with visual studio 2019 with default compiler and c++11 version
Last edited on
Works just fine for me:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <memory>

using namespace std;

template <typename T> struct structure {
	int i;
	char c;
	T t;
};

template <typename T> class test {
public:
	test();
	void function();
private:
	unique_ptr<structure<T>> ptr;
};

template <typename T> test<T>::test() {
	ptr.reset(new structure<T>);
}

template<typename T> void test<T>::function() {
	ptr->i = 7;
	cout << ptr->i;
}

int main()
{
    test<int> t;
    t.function();
}
I'm so sorry, i've just noticed an error in the rest of my program that i hadn't copy there.
I 've see the wrong error before copying it there.

You're right this is working!
Last edited on
Topic archived. No new replies allowed.