Heim > Artikel > Backend-Entwicklung > Wie kann die Typkonsistenz in variadischen Funktionen ohne zusätzliche Strukturen erzwungen werden?
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> dragon_list_t make_dragon_list(Items... maidens) { std::array<Maiden, sizeof...(Items)> arr = {{ maidens ... }}; // here be dragons }
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<typename R, typename...> struct fst { typedef R type; }; template<typename ...Args> typename fst<void, typename enable_if< is_convertible<Args, ToType>::value >::type... >::type f(Args...);
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.
Das obige ist der detaillierte Inhalt vonWie kann die Typkonsistenz in variadischen Funktionen ohne zusätzliche Strukturen erzwungen werden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!