Make Template Class Return Template Type?

Hello there!

Sorry if the title doesn't explain this well. But the code should explain it.

So I have a template class called NetworkVar:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
template < typename T >
class NetworkVar : public INetworkVar
{
public:
	NetworkVar()
	{
		m_bStateChanged = false;
		m_Size = sizeof( T );
	}

	NetworkVar &operator=( T rhs )
	{
		m_Var = rhs;
		m_bStateChanged = true;
		return *this;
	}

	operator T() const
	{
		return m_Var;
	}

	operator T&()
	{
		return m_Var;
	}

	T Get()
	{
		return m_Var;
	}

	void *data() override
	{
		return ( void * )( &m_Var );
	}

	size_t sizeofElement() override
	{
		return m_Size;
	}

	bool StateChanged() override
	{
		return m_bStateChanged;
	}

protected:
	// Size can be overriden by network table to ensure consistent size across platforms
	void SetSize( size_t size )
	{
		m_Size = size;
	}

	void SetData( char *pData )
	{
		std::memcpy( ( void* )&m_Var, ( void* )pData, sizeofElement() );
		m_bStateChanged = false;
	}

private:
	T m_Var;

	bool m_bStateChanged;
	size_t m_Size;
};


So for instance I can declare a network variable like so:

NetworkVar< int > myInt;

Now I already have operators:

1
2
3
4
5
6
7
8
9
operator T() const
{
	return m_Var;
}

operator T&()
{
	return m_Var;
}


This returns the type used in the template. However, this doesn't work for everything. For instance if I want to do printf( "myInt is %d\n", myInt ); It's not printing the integer value of myInt, I'm printing some garbage data.

I can also have a .Get() function that also returns the m_Var above, but if it's possible to avoid that, I would prefer it.
Last edited on
1
2
// printf( "myInt is %d\n", myInt );
printf( "myInt is %d\n", int(myInt) );

Ideally, leave type-unsafe functions like printf and the like to the C crowd.

This would perform the implicit conversion automatically: std::cout << "myInt is: " << myInt << '\n' ;
Yeah, ha, I'm trying to break away from C functions, but they've gotten so ingrained in me. Still, the implicit conversion would be useful for those kinds of functions. I'd rather avoid casting altogether. But it seems that it's unavoidable.
Topic archived. No new replies allowed.