jeudi 28 décembre 2017

Template specialization and perfect forwarding

So I am trying to build a "sanitizer" function to filter formatting arguments before they are forwarded to printf.

template<typename A>
_CR_INLINE decltype(auto) sanitize_forward(A&& arg) {
    return std::forward<A>(arg);
}

template<>
_CR_INLINE decltype(auto) sanitize_forward<std::string>(std::string&& arg) {
    return std::forward<const char*>(arg.c_str());
}

So every std::string is supposed to "decay" into a const char*, in order to be properly formatted.

template<typename...Args>
_CR_INLINE void printf_safe(const std::string& format, Args&&...args) {
    std::printf(format.c_str(), sanitize_forward<Args>(args)...);
}

I want the arguments to be perfectly forwarded to printf, which is why I return std::forward. But I can't really wrap my head around how this should be implemented.

1) Is decltype(auto) correct? It should preserve the r-value referenceness of the return of std::forward, right?

2) How should I specialize my template: std::string&& or std::string?

3) Deduced forwarding references should be the same as the actual type, right?

Aucun commentaire:

Enregistrer un commentaire