简体   繁体   中英

template class specialization at template constructor

Is it possible to specify a template constructor ONLY for a specific specialization of its template class? I have this code:

template <typename T>
class A {
public:
    A(std::function<T()> f) : x(f) {}

    template <typename Y>
    A<void>(Y* x) : x(x) {}
private:
    boost::variant<int*, char*, std::function<T()>> x;
}

I am trying to make the second constructor compile only for non-std::function parameters, that's why I'm trying to find a way to explicitly tell the compiler that T should be void in this case, but obviously this won't compile.

You can use SFINAE and additional parameter with default value

template <typename T>
struct is_std_function : public std::false_type {};

template <typename T>
struct is_std_function<std::function<T> > : public std::true_type{};    

template <typename T>
class A {
public:
    A(std::function<T()> f) : x(f) {}

    template <typename Y>
    A(Y* x, typename std::enable_if< !is_std_function<Y>::value >::type * = 0) : x(x) {}
private:
    boost::variant<int*, char*, std::function<T()>> x;
}

Now for std-function types your constructor can't be specialized due to the second parameter.

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