A A
A A

Reputation: 41

C++ deduction guides for auto types

C++17 allows to create deduction guides for classes. Are they possible to be applied with autos as well?

Here is a quick example of what I'm trying to achieve:

#include <stdio.h>

struct Rect
{
    int Rect;
};

template<typename T, int k = 0>
class TemplatedClass : public T
{
public:
    static constexpr int S = k;

    T value;
 
    TemplatedClass() {}
    TemplatedClass(T val) : value(val) {}
};

TemplatedClass(TemplatedClass<Rect, 0>) ->TemplatedClass<Rect, 66>;

TemplatedClass<Rect, 0> DrawRect() 
{
    return {};
}

int main()
{
    auto r = DrawRect();
    r.Rect = 0;

    TemplatedClass a = DrawRect();
    a.Rect = 0;

    printf("r.S %d \n", r.S); // Should be 66
    printf("a.S %d \n", a.S); // Should be 66


    return 0;
}

The code returns 0 for the auto variable. Is there any way I can make it fallback to the deduction guide created? The function still must remain with template k = 0.

I understand that auto is meant to use the return type of the function, but maybe there are any tricks to override this type?

https://godbolt.org/z/PoefK5dnK

Upvotes: 2

Views: 126

Answers (1)

Gon&#231;alo Gomes
Gon&#231;alo Gomes

Reputation: 90

Humm I don't get this.

You're saying a TemplatedClass without any template parameters is TemplatedClass<Rect, 66>

As the function is explicitly returning TemplatedClass<Rect, 0> then the auto behaviour is correct.

The other use case you're just creating one type based on the other, based on the deduction guide.

may there be any tricks to override this type

Yes, you've done it already.

 TemplatedClass a = DrawRect();

or

TemplatedClass<Rect, 66> DrawRect() 
{
    return {};
}

but honestly, that's not how most people would use deduction guides, it makes the code very very confusing, if you want the DrawRect function to return a class with the literal 66 then just do that.

Upvotes: 1

Related Questions