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++?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With