C ++模板专业化:更改operator()的返回类型?

时间:2015-11-02 02:05:57

标签: c++ templates c++14 template-specialization return-type

在下面的课程中,我定义了operator()返回return_T的向量:

#include <vector>

template <typename return_T, typename ... arg_T>
class A
{
public:
    std::vector<return_T> operator()(arg_T... args);
};

除了return_T = void之外,这是有效的,因为vector<void>是不可能的。因此,我需要以某种方式定义A<void, arg_T>::operator()的特化。我正在尝试使用以下代码:

#include <vector>

template <typename return_T, typename ... arg_T>
class A
{
public:
    auto operator()(arg_T... args);
};

template<typename return_T, typename... arg_T>
auto A<return_T, arg_T...>::operator()(arg_T... args) -> typename std::enable_if<!std::is_void<return_T>::value, std::vector<return_T>>::type
{ }

template<typename return_T, typename... arg_T>
auto A<void, arg_T...>::operator()(arg_T... args) -> void
{ }

但是编译器并不喜欢它。

error : prototype for 'typename std::enable_if<(! std::is_void<_Tp>::value), std::vector<_Tp> >::type A<return_T, arg_T>::operator()(arg_T ...)' does not match any in class 'A<return_T, arg_T>'
   auto A<return_T, arg_T...>::operator()(arg_T... args) -> typename std::enable_if<!std::is_void<return_T>::value, std::vector<return_T>>::type

error : candidate is: auto A<return_T, arg_T>::operator()(arg_T ...)
       auto operator()(arg_T... args);
            ^

error : invalid use of incomplete type 'class A<void, arg_T ...>'
   auto A<void, arg_T...>::operator()(arg_T... args) -> void
                                                        ^

当然,我可以轻松地用void operator()写第二堂课,但我很好奇是否可以用一门课来完成。所以我的问题是:这可能吗?

2 个答案:

答案 0 :(得分:4)

您可以创建一个专门的“traits”类,而不是专门化A

template <typename return_T>
struct Traits {
    using ReturnType = std::vector<return_T>;
};

template <>
struct Traits<void> {
    using ReturnType = void;
}

template <typename return_T, typename ... arg_T>
class A
{
public:

    typename Traits<return_T>::ReturnType operator()(arg_T... args);
};

通过这种方式,您不必专门化A,如果A很大,这可能会很方便,而且专门化它会比专门化小型特征类更复杂。

答案 1 :(得分:4)

#include <type_traits>
#include <utility>
#include <vector>

template <typename return_T, typename... arg_T>
class A
{
public:
    auto operator()(arg_T... args)
    {
        return invoke(std::is_void<return_T>{}, std::forward<arg_T>(args)...);
    }

private:
    void invoke(std::true_type, arg_T&&... args)
    {
    }

    std::vector<return_T> invoke(std::false_type, arg_T&&... args)
    {
        return {};
    }
};

测试:

int main()
{
    A<int, char, short> a;    
    static_assert(std::is_same<decltype(a('x', 5)), std::vector<int>>{}, "!");

    A<void, char, short> b;
    static_assert(std::is_same<decltype(b('x', 5)), void>{}, "!");    
}

DEMO