0

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;
}
4
  • 1
    What errors are you getting? Without posting the errors, this isn't a minimal reproducible example Commented Jan 24, 2018 at 20:58
  • Thanks Francois, seems it was my misunderstanding. I was under the impression floats and doubles were similar but a double was larger and more precise. How would I improve my example to avoid this error? Is a simple cast sufficient? Commented Jan 24, 2018 at 21:03
  • Yes, an MCVE is required. However, in addition, throwing the error message into a websearch also prevents asking redundant questions in the first place. Commented Jan 24, 2018 at 21:03
  • @Iloveasparagus I've made an answer from my comment. It contains a possible change to fix your problem. Commented Jan 24, 2018 at 21:04

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Change the previous line to float y = 5.1f; As it stands, the program is telling the compiler to create a double(5.1) and then narrow it to float. VC++ gives the warning, warning C4305: 'initializing': truncation from 'double' to 'float'
3

&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.

1 Comment

Change the previous line to float y = 5.1f; As it stands, the program is telling the compiler to create a double(5.1) and then narrow it to float. VC++ gives the warning, warning C4305: 'initializing': truncation from 'double' to 'float'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.