haskeller
haskeller

Reputation: 151

how to make a template function like R f<void(int)>(args...)

now i want to create a function looked like f<void(int)>(args...),my code is:

template<typename T>
struct A{};

template<typename F>
A<F> f4();

template<typename R,typename... Args>
A<R(Args...)> f4<R(Args...)>() {
    return A<R(Args...)>();
}

but it does not work and vs gives error C2768

how can i do that?

Upvotes: 0

Views: 59

Answers (1)

songyuanyao
songyuanyao

Reputation: 173044

You can't partial specialize function template; class template can. e.g.

// primary template
template<typename F>
struct f4_s {
    static A<F> f4() {
        return A<F>();
    }
};

// partial specialization
template<typename R,typename... Args>
struct f4_s<R(Args...)> {
    static A<R(Args...)> f4() {
        return A<R(Args...)>();
    }
};

template<typename T>
auto f4() {
    return f4_s<T>::f4();
}

then

f4<int>();           // call the primary version
f4<int(int,char)>(); // call the specialization version

LIVE

Or apply overloading with function templates. e.g.

template<typename F>
std::enable_if_t<!std::is_function_v<F>, A<F>> f4() {
    return A<F>();
}    

template<typename F>
std::enable_if_t<std::is_function_v<F>, A<F>> f4() {
    return A<F>();
}

then

f4<int>();           // call the 1st overload
f4<int(int,char)>(); // call the 2nd overload

LIVE

Upvotes: 1

Related Questions