I have created a templated struct and am trying to overload the binary operators. For some reason the function does not return the correct data type even though the type is correctly casted in between.
template<typename T>
struct Number{
const T value;
Number(T a) : value(a) {}
template<typename U>
auto operator*(Number<U> other){
auto new_value = value*other.value;
std::cout << typeid(new_value).name() << std::endl;
return Number(new_value);
}
};
Now if I perform this operation with the following code called in main. It returns Number of the type of the first one, not number of the higher type.
auto b = Number<int>(6) * Number<double>(2.3); // this should be an int*double=double
std::cout << b.value << typeid(b.value).name() << std::endl;
auto c = Number<double>(2.3) * Number<int>(6);
std::cout << c.value << typeid(c.value).name() << std::endl;
Output is as follows: d 13i d 13.8d
From what I understand, the incorrect constructor is called when the function return the new Number(new_value)
. I do not understand how and why this happens as new_value is of the 'correct type'.
In C++14, you can just use auto as a return type.
Class Template Argument Deduction (CTAD) is a C++17 Core Language feature that reduces code verbosity. C++17's Standard Library also supports CTAD, so after upgrading your toolset, you can take advantage of this new feature when using STL types like std::pair and std::vector.
An Auto-Template is a pre-configured set of Automations you can build and save. You can then reference them manually or use them in an Automated Workflow. CLICK HERE to learn about Automations.
Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.
Inside the scope of a template, the template-name is going to stand for the injected class name, and not for the template. So there will not be CTAD, and that's by design
Using return Number<decltype(new_value)>(new_value);
is the simple workaround.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With