Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class' constructor arguments

Is there any way to get the parameters of a constructor in C++?

template <typename T>
class Test {
 public:
  // Get the constructor arguments from class T
  Test(constructor<T>());

 private:
  T* value_;
};

template <typename T>
Test(constructor<T>()) {
  value_ = new T(constructor);
}

int main() {
  // std::string can be initialized by string literal
  Test<std::string> test("Text");
  return 0;
}

I know I can just use T as the argument but I don't want to pass the object itself, just the parameters it takes.

Anyway of doing this in standard C++?

like image 480
Lunatoid Avatar asked Sep 05 '25 02:09

Lunatoid


1 Answers

I don't know what "vanilla" C++ is, but what you can do is accept any arguments which the other class allows, and forward them:

template <typename T>
class Test {
public:
  template <class... Args,
      std::enable_if_t<std::is_constructible<T, Args&&...>::value, int> = 0>
  Test(Args&&... args)
      : value_(std::forward<Args>(args)...)
  { }

  Test(T&& val)
      : value_(std::move(val))
  { }

private:
  T value_;
};

The second constructor there is to allow passing a brace-init-list into the Test constructor. This still isn't quite a perfect stand-in, but it's pretty good.

like image 63
Barry Avatar answered Sep 07 '25 14:09

Barry