C++模板专用化:更改运算符()的返回类型

C++ template specialization: change return type of operator()?

本文关键字:运算符 返回类型 专用 C++      更新时间:2023-10-16

在下面的类中,我定义了一个返回return_T向量的operator()

#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()编写第二个类,但我很好奇是否也可以用一个类来完成。所以我的问题是:这可能吗?

#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

您可以创建一个专门化的"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很大,并且专门化它会比专门化一个小的特征类更复杂,这会很方便。