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.
위 내용은 추가 구조 없이 Variadic 함수에서 유형 일관성을 적용하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!