0

There are no problems compiling this code:

struct A
{
    template<typename T>
    void f(int) {}
};

A a;
a.f<double>(42);

However, similar code with templated constructor does not compile:

struct A
{
    template<typename T>
    A(int) {}
};

A a<double>(42);

Gcc gives the following error in the last line: error: unexpected initializer before '<' token

Is there a way to make constructor example work?

user2052436
  • 4,321
  • 1
  • 25
  • 46

1 Answers1

2

There is no way to explicitly specify templates for a constructor, as you cannot name a constructor.

Depending on what you're trying to do, this can be used:

#include <iostream>
#include <typeinfo>

struct A
{
    template <typename T>
    struct with_type {};

    template<typename T>
    A(int x, with_type<T>)
    {
        std::cout << "x: " << x << '\n'
                  << "T: " << typeid(T).name() << std::endl;
    }
};

int main()
{
    A a(42, A::with_type<double>());
}

This "cheats" by taking advantage of type deduction.

This is quite unorthodox, though, so there's probably a better way of doing what you need.

GManNickG
  • 494,350
  • 52
  • 494
  • 543