不带参数的部分特化函数模板

partially specialize function template with no parameters

我认为这是不可能的,但必须有人知道得更多...

template<typename T>   
T Read()   //T is int, char, etc
{
    return read<T>();
}

template<typename T, Size> 
std::array<T,Size> Read<std::array<T, Size>>()
{
     return unique_read<T, Size>();
}

我想一旦我指定了任何模板参数,它就不再是完全特化,函数中不允许部分特化

我唯一能想到的是:

template<typename T>
struct _dummy
{
    T Read() {
        return T();
    };
};

template<typename T, size_t Size>
struct _dummy<std::array<T, Size>>
{
    using ArrayType = std::array<T, Size>;

    ArrayType Read() {
        return ArrayType();
    };
};

你应该为这种工作使用标签调度:

namespace detail {
template<class T>struct tag{};

template<class T>
T Read(tag<T>) {
    return T{};
}

template<class T, std::size_t N>
std::array<T, N> Read(tag<std::array<T, N>>) {
    return {1,2,3};
}
}

template<class T>
auto Read() {
    return detail::Read(detail::tag<T>());
}

int main() {
    Read<std::array<int,5>>();
}

另一种方法是使用函数对象:

template<class T> 
struct reader_op {
  T operator()() const { 
    // whatever needs to happen here
  }
};

// partially specialise for array case
template<class T, size_t N> 
struct reader_op<std::array<T, N>> {
  std::array<T, N> operator()() const { 
    // whatever needs to happen here
  }
};

// reader_op class type is now deduced from T
// when T is a std::array, our specialised function object will
// be used
template<typename T>   
T Read()   //T is int, char, etc
{
    return reader_op<T>()();
}