kkm kkm - 1 year ago 108
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

when creating its instance in the
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
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download