简体   繁体   中英

Type trait for member template static function

I have a problem with type traits in C++. I'm used to make SFINAE checks to ensure that a function exist or not. However, I would like to have a trait that can tell if a class has a specific template member static function.

This example will help explain my problem. Let's pretend that the doMake function takes a function pointer as parameter and its arguments as a pack.

struct A {
    static A construct(int mA, double mB) {
        return A{mA, mB};
    }

    int a;
    double b;
};

struct B {
    // silly but some of my code need this
    template<typename T>
    static B construct(int mA, T mB) {
        return B{mA, mB};
    }

    int a;
    double b;
};

struct Container {
    // function (1)
    template<typename T, typename... Args,
        typename std::enable_if<has_template_construct<T>::value, int>::type = 0>
    T make(Args&&... args) {
        return doMake(&T::construct<Args...>, std::forward<Args>(args)...);
    }

    // function (2)
    template<typename T, typename... Args,
        typename std::enable_if<has_construct<T>::value, int>::type = 0>
    T make(Args&&... args) {
        return doMake(&T::construct, std::forward<Args>(args)...);
    }

    // function (3)
    template<typename T, typename... Args,
        typename std::enable_if<!has_construct<T>::value, int>::type = 0>
    T make(Args&&... args) {
        return T{std::forward<Args>(args)...};
    }
};

// ...

int main() {
    Container c;
    auto a = c.make<A>(1, 5.7); // would call (2)
    auto b = c.make<B>(2, 5.8); // would call (1)
    auto d = C.make<float>(4.f); // obviously call the last
    return 0;
}

I know how to implement has_construct , but I'm quite lost at how to implement has_template_construct . Can someone give me some hints? Thanks!

With experimental is_detected you may do:

template<class T>
using construct_t = decltype(&T::construct);

template<class T, typename...Ts>
using template_construct_t = decltype(&T::template construct<Ts...>);

template <typename T>
using has_construct = is_detected<construct_t, T>;

template <typename T, typename...Ts>
using has_template_construct = is_detected<template_construct_t, T, Ts...>;

Note that in function1 , you will have to use has_template_construct<T, Args...>::value ( ,Args... added).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM