Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template with auto-type return deduction

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

like image 956
Helvijs Sebris Avatar asked Dec 17 '18 09:12

Helvijs Sebris


People also ask

Can auto be a return type?

In C++14, you can just use auto as a return type.

What is template argument deduction?

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.

What is auto template?

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.

What is C++ type deduction?

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.


1 Answers

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.

like image 181
StoryTeller - Unslander Monica Avatar answered Sep 20 '22 22:09

StoryTeller - Unslander Monica