我的目的很簡單,輸入的資料型別取決于模板 bool:
template<bool isfloa>
class example{
public:
if (isfloa){
example(float p){printf("sizeof p: %d\n", sizeof(p))};
} else{
example(uint64_t p){printf("sizeof p: %d\n", sizeof(p))};
}
};
這無法通過編譯,我有以下解決方案(尚未測驗):
using dataType = isfloa ? float : uint64_t;
example(dataType p){printf("sizeof p: %d\n", sizeof(p))};
我想知道這是否有效?還有其他解決方案嗎?非常感謝。
uj5u.com熱心網友回復:
您可以使用 std::conditional
template<bool isfloat>
class example{
public:
using value_type = std::conditional_t<isfloat,float,int>;
example(value_type p){printf("sizeof p: %d\n", sizeof(p));}
};
uj5u.com熱心網友回復:
在 C 17 中,您可以使用 sfinae 來禁用或啟用成員函式:
template<bool isfloa>
class example{
public:
template<bool isf = isfloa, std::enable_if_t<isf, int> = 0>
example(float p){ printf("sizeof p: %d\n", sizeof(p)); }
template<bool isf = isfloa, std::enable_if_t<!isf, int> = 0>
example(uint64_t p){ printf("sizeof p: %d\n", sizeof(p)); }
}
};
在 C 20 中,您可以簡單地使用requires關鍵字:
template<bool isfloa>
class example{
public:
example(float p) requires(isfloa)
{ printf("sizeof p: %d\n", sizeof(p)); }
example(uint64_t p) requires(!isfloa)
{ printf("sizeof p: %d\n", sizeof(p)); }
}
};
uj5u.com熱心網友回復:
更喜歡使用正常的函式多載,然后在需要的地方切換到模板。在這種情況下,對兩種浮點型別重用相同的代碼。
#include <type_traits> // header file for all kinds of type related checks at compile time
#include <iostream>
// for std::uint64_t only just use standard overloading
// NO need to overuse templates and template specializations where none is needed.
void example(const std::uint64_t value)
{
std::cout << "std::uint64_t, value = " << value << "\n";
}
// use SFINAE (std::enable_if_t) to enable this version of the function only for floating point types
template<typename type_t>
static inline std::enable_if_t<std::is_floating_point_v<type_t>, void> example(const type_t& value)
{
std::cout << "floating point value, value = " << value << "\n";
}
int main()
{
double fp{ 3.14159265 };
example(fp);
std::uint64_t value{ 42 };
example(value);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375296.html
上一篇:我可以以某種方式優雅地禁止在我的模板函式中使用未標記的變數嗎?
下一篇:模板型別決議失敗
