A beginner's question here, so I have the following code
foo.h
enum class Fruit : uint16_t {
Apple = 8019U,
Orange = 8020U,
Banana = 8021U,
Cactus = 8022U
};
class Foo {
public:
template<typename T> void SetValue(unsigned int location, const T& value);
template<typename T> void SetValue(unsigned int location, const T* value_ptr);
template<typename T> void SetValue(Fruit fruit, const T& value);
template<typename T> void SetValue(Fruit fruit, const T* value_ptr);
}
foo.cpp
template<typename T>
void Foo::SetValue(unsigned int location, const T& value) {
std::cout << value << std::endl;
}
template<typename T>
void Foo::SetValue(unsigned int location, const T* value_ptr) {
std::cout << (*value_ptr) << std::endl;
}
template<typename T>
void Foo::SetValue(Fruit fruit, const T& value) {
SetValue<T>(static_cast<unsigned int>(fruit), value);
}
template<typename T>
void Foo::SetValue(Fruit fruit, const T* value_ptr) {
SetValue<T>(static_cast<unsigned int>(fruit), value_ptr);
}
#define INSTANTIATE_TEMPLATE(T) \
template void Foo::SetValue<T>(unsigned int location, const T& value); \
template void Foo::SetValue<T>(unsigned int location, const T* value_ptr); \
template void Foo::SetValue<T>(Fruit fruit, const T& value); \
template void Foo::SetValue<T>(Fruit fruit, const T* value_ptr);
INSTANTIATE_TEMPLATE(int)
INSTANTIATE_TEMPLATE(uint)
INSTANTIATE_TEMPLATE(bool)
INSTANTIATE_TEMPLATE(float)
INSTANTIATE_TEMPLATE(vec2)
INSTANTIATE_TEMPLATE(vec3)
INSTANTIATE_TEMPLATE(vec4)
INSTANTIATE_TEMPLATE(mat2)
INSTANTIATE_TEMPLATE(mat3)
INSTANTIATE_TEMPLATE(mat4)
...
#undef INSTANTIATE_TEMPLATE
main.cpp
int main() {
Foo foo;
float bar[7] { 0.0f, 0.15f, 0.3f, 0.45f, 0.6f, 0.75f, 0.9f };
float baz = 12.5f;
foo.SetValue(Fruit::Orange, 1.05); // calling SetValue<double>(Fruit fruit, const double& value)
foo.SetValue(Fruit::Apple, bar + 3); // calling SetValue<float*>(Fruit fruit, float *const& value)
foo.SetValue(Fruit::Cactus, &baz); // calling SetValue<float*>(Fruit fruit, float *const& value)
}
In the last 2 calls, while I really intended to call
SetValue<float>(Fruit fruit, const float* value_ptr)
What actually gets called are
SetValue<float*>(Fruit fruit, float *const& value)
I'm aware that this is ambiguous because VS Intellisense was not able to color highlight SetValue<T>
in the overridden function body, so I tried to write foo.SetValue<float>(Fruit::Cactus, &baz)
instead, now the compiler interprets T
as float
rather than float*
, but I wonder if this is a horrible design...... Is there a better approach that doesn't require me to explicitly specify the type of T
? How can I eliminate the ambiguity completely?