Maison > développement back-end > C++ > le corps du texte

Comment appliquer la cohérence des types dans les fonctions variadiques sans structures supplémentaires ?

DDD
Libérer: 2024-11-13 12:59:02
original
891 Les gens l'ont consulté

How to Enforce Type Consistency in Variadic Functions Without Additional Structures?

Enforcing Type Consistency in Variadic Functions Without Additional Structures

Variadic functions and variadic template functions allow us to pass a variable number of arguments to a function. However, ensuring that all arguments have the same type can be challenging. This question explores a solution for this problem without using arrays, vectors, or structs.

Variadic Function Approach

The proposed solution is to accept arguments by the variadic template and let type checking verify validity when they are converted. However, this approach requires us to have a known conversion path to the desired type. In this case, there must be a known way to convert an array of Maiden to dragon_list_t.

Example:

template<typename ...Items&gt;
dragon_list_t make_dragon_list(Items... maidens) {
    std::array<Maiden, sizeof...(Items)&gt; arr = {{ maidens ... }};
    // here be dragons
}
Copier après la connexion

SFINAE Approach

SFINAE (Substitution Failure Is Not An Error) can be used to enforce type consistency at the function interface level. This allows us to reject invalid arguments early in the overload resolution process.

Example:

template&lt;typename R, typename...&gt; struct fst { typedef R type; };

template&lt;typename ...Args&gt;
typename fst&lt;void, 
  typename enable_if&lt;
    is_convertible&lt;Args, ToType&gt;::value
  &gt;::type...
&gt;::type 
f(Args...);
Copier après la connexion

Conclusion

Both approaches provide a way to specify one type for all arguments passed to variadic functions without using additional data structures. The variadic function approach relies on known conversion paths, while the SFINAE approach allows for overload resolution to reject invalid arguments. The choice between these approaches depends on the requirements of the specific use case.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal