Iloveasparagus
Iloveasparagus

Reputation: 1

Template Function using Pointers

am I doing something fundamentally wrong here? I'm playing around with templates and pointers but I'm getting errors here.

#include <iostream>
#include <string>

template <class T>
void ChangeValue(T*, T);

int main()
{
int x = 51;

ChangeValue(&x, 7);

std::cout << x;

float y = 5.1;

ChangeValue(&y, 7.9);

std::cout << y;
}

template <class T>
void ChangeValue(T* Value, T NewValue)
{
    *Value = NewValue;
}

Upvotes: 0

Views: 54

Answers (2)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29023

&y has the type float* where as 7.9 has the type double. The compiler could deduce T to be float by matching float* to T* Value or it could deduce double by matching double to T NewValue. For template argument deduction to succeed it must be unambiguous. Try this instead :

float y = 5.1f;
ChangeValue(&y, 7.9f);

With this change, T is deduced to be float.

Upvotes: 3

R Sahu
R Sahu

Reputation: 206567

When you use:

float y = 5.1;
ChangeValue(&y, 7.9);

The type of the first argument is float* while the type of the second argument is double. Hence, the compiler cannot deduce T.

One way to fix it is by using:

template <typename T1, typename T2 = T1>
void ChangeValue(T1* Value, T2 NewValue)
{
    *Value = NewValue;
}

With that, T2 is deduced from T1 unless the user explicitly overrides it.

float y = 5.1;
ChangeValue<float, double>(&y, 7.9);

What would work as long as

    *Value = NewValue;

is valid for the given T1 and T2.

Upvotes: 3

Related Questions