kkm kkm - 1 month ago 10
C++ Question

How to resolve constructor signature in factory function

I want to support one of two possible signatures of the constructor of the class

T
when creating its instance in the
create(...)
function below:

template <class ΠΆ, typename... Args>
T* create(Special* s, Args&&... args) {
T* t =
// If such a constructor exists, this:
new T(s, std::forward<Args>(args)...);
// Otherwise, this:
new T(std::forward<Args>(args)...);
}


I tried a few monstrous template constructions that did not cut it. The solution for resolving a member function involves SFINAE-failing a
decltype
of a member function, but this is not apparently possible with a constructor, as it does not have a signature type of its own.

Is this even possible in C++11, and is there any library support?

Answer

Just use std::is_constructible:

namespace detail
{
template<typename T, typename... Ts>
auto create(std::true_type, Special* s, Ts&&... args) {
    return new T(s, std::forward<Ts>(args)...);
}

template<typename T, typename... Ts>
auto create(std::false_type, Special*, Ts&&... args) {
    return new T(std::forward<Ts>(args)...);
}

}

template<class T, typename... Args>
T* create(Special* s, Args&&... args) {
    using tag = is_constructible<T, Special*, Args...>;
    return detail::create<T>(tag{}, s, std::forward<Args>(args)...);
}

live demo