简体   繁体   English

没有参数的部分专用功能模板

[英]partially specialize function template with no parameters

I think it's not possible but someone must know better... 我认为这是不可能的,但必须有人更了解...

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>();
}

I guess as soon as I specify any template argument it's no longer a full specialization, and partial specialization is not allowed in functions 我想一旦指定任何模板参数,它就不再是完全专业化,并且函数中不允许部分专业化

The only thing I could come up with is: 我唯一能想到的是:

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();
    };
};

You should use tag dispatching for this sort of job: 您应将标签分派用于此类工作:

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>>();
}

The other way to do this is to defer to a function object: 执行此操作的另一种方法是遵循一个函数对象:

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>()();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM