Templated auto-assignment

Started by
1 comment, last by Antheus 15 years, 9 months ago
I am trying to make a template class that will hold me variables to be used with a shader class. These classes pretty much hold the variable itself and its type (an enum value). Here is how the code works:

enum VarType
{
	VT_Bool1,
	VT_Bool2,
	VT_Bool3,
	VT_Bool4,
	VT_Float1,
	VT_Float2,
	VT_Float3,
	VT_Float4,
	VT_Mat2x2,
	VT_Mat3x3,
	VT_Mat4x4,
};

// ===========================

template<class T>
class ShaderVar
{
	VarType variableType;
	T var;

public:

	ShaderVar(const T &initValue = T());
	~ShaderVar();

	// Getters
	VarType getVariableType() const;
	T &getVariable();

	// Setters
	Void setVariable(const T &v);
};


What I'm trying to achieve is auto-assignment of the VarType variable when the user instantiates the class with a certain template declaration:

ShaderVar<Matrix3x3> foo;


Internally it would assign the variables the following way: ShaderVar::var = Matrix3x3() ShaderVar::variableType= VT_Mat3x3 I believe there is a way of doing this way using templates, I just cant remember the syntax. EDIT: Alternatively, I can pass in two variables into the template and type def the class into its own type. But I would like to explore the above instance first.

typedef ShaderVar<Matrix3x3, VT_Mat3x3> ShaderMat3x3;

------------Anything prior to 9am should be illegal.
Advertisement
1) You don't need to worry about "ShaderVar::var = Matrix3x3()", since the default constructor will be called on type T, which will be Matrix3x3. So it does that for you already.

2) The first option can be done:

template <typename T> struct var_type;template <> struct var_type<Matrix3x3> { enum { type = VT_Mat3x3 }; };template <> struct var_type<Matrix4x4> { enum { type = VT_Mat4x4 }; };// ... repeat for every option ...// in your constructorShaderVar::variableType = typename var_type<T>::type;


I won't comment on whether or not your design is a good way of doing things, but that's how you can do it with template metaprogramming.
[ search: google ][ programming: msdn | boost | opengl ][ languages: nihongo ]
The enum you want is redundant. The T itself is your enum, since if you try to test for a value, it'll result in compile-time constant anyway. Enums are used for dynamic types.

Just do:
template < class T >struct ShaderVar {  typedef T value_type;  T storage;};
And then, if you need specific processing for type:
void foo(ShaderVar<Matrix3x3> & bar);


The T acts as your enum. You don't need anything else. If you encounter a problem where you'd need to test for a specific value (if T == a) else if (T == b) else if (T == c) ....., then you might need to reconsider the approach, and convert it to functional approach as above. Fortunately, it's easily achievable with free functions.

This topic is closed to new replies.

Advertisement