1

I have recently adopted the pattern of Almost Always Auto in C++14, but have come across a case that I can't figure out how to write using the auto syntax: templated constructors.

Say I have the class:

class my_type{
    public:
        template<typename T>
        my_type(){/* ... */}
};

I tried:

auto var = my_type<float>{};

Which, of course, doesn't work because that presumes my_type is a template and not its constructor.

then how could I use auto syntax to initialize this variable?

RamblingMad
  • 5,332
  • 2
  • 24
  • 48

1 Answers1

1

Although it isn't really about auto, there is a way to select templated ctors if you want to - you need to cheat, and give them an argument.

struct A {
private:
    template <typename T> struct TypeWrapper {};
    template <typename T> explicit A(TypeWrapper<T>) {}
public:
    template <typename T>
    static A make_A() {
        return A(TypeWrapper<T>{});
    }
};

int main() {
    auto i = A::make_A<int>();
    auto d = A::make_A<double>();
    auto r = A::make_A<A>();
    // etc. etc.
}
Useless
  • 64,155
  • 6
  • 88
  • 132