我想知道在C 中是否有辦法區分ASCII值和數字,例如'A'和65的值都是65,但如何區分它們?
假設我們想將兩個數字相加,那么sum(10,65)應該回傳75,但是sum(10,'A')應該回傳0。此外,請記住,sum()的引數應該具有相同的型別,即double。
uj5u.com熱心網友回復:
使用多載函式。它與你的條件相當簡短(對于所有非雙倍的引數型別回傳0):
double sum(double a, double b) { return a b。}
template <typename A, typename B>
double sum(A a, B b) { return 0; }
uj5u.com熱心網友回復:
在C 17及以后的版本中,你可以讓sum()成為一個模板函式,然后使用if constexpr來讓sum()根據它實際傳遞的引數型別進行決策,例如:
#include <iostream>
#include <type_traits>
template <typename T, typename...。Ts>。
inline constexpr bool is_any_v = (... || std::is_same_v<T, Ts>)。
template <typename T>
inline constexpr bool is_char_v = is_any_v< T, char, wchar_t, char16_t, char32_t> 。
template<typename T>
inline constexpr bool is_arithmetic_not_char = std::is_arithmetic_v<T> & & !is_char_v<T> 。
template<typename A, typename B>
double sum(A a, B b) {
if constexpr (is_arithmetic_not_char<A> && is_arithmetic_not_char<B> )
return a b。
else
return 0;
}
int main()
{
std::cout << sum(10, 65)<< std::endl; //75sum(10, 'A') << std::endl; // 0
return 0。
}
std::is_arithmetic特質只對積分型別和浮點型別為真,而對所有其他型別為假。問題是,字符型別,如char,也是積分型別。因此,這段代碼允許 sum() 只有在呼叫不屬于字符型別的算術型別時才能真正計算出一個結果,否則它將對其他所有型別回傳 0。
然而,你的問題被標記為C 11和C 14,在這些版本中,if constexpr不可用(與fold expressions),但你可以使用std::enable_if來代替,使用SFINAE完成類似作業,例如:
#include <iostream>
#include <type_traits>
template<typename T>
constexpr bool is_char_v = std::is_same<T,char>:value || std:: is_same<T,wchar_t>::value || std::is_same<T,char16_t>::value || std::is_same<T,char32_t>::value。
template<typename T>
constexpr bool is_arithmetic_not_char = std::is_arithmetic<T>:value && !is_char_v< T>。
template<typename A, typename B, typename std: :enable_if<is_arithmetic_not_char<A>&&is_arithmetic_not_char<B>, int> :type = 0>
double sum(A a, B b) {
return a b;
}
template<typename A, typename B, typename std::enable_if<! (is_arithmetic_not_char<A> && is_arithmetic_not_char<B>), int> :type = 0>
double sum(A, B) {
return 0;
}
int main()
{
std::cout << sum(10, 65)<< std::endl; //75sum(10, 'A') << std::endl; // 0
return 0
}
uj5u.com熱心網友回復:
isdigit()函式對你有用嗎?
char value = 'A'/span>。
if (isdigit(value))
sum(10, value)。
else[/span
sum(0, 0) 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/314122.html
標籤:
