所以我有這兩個功能:
bool intComp(int a, int b)
{
return a > b;
}
bool stringComp(std::string a, std::string b)
{
return strcmp(a.c_str(), b.c_str()) > 0;
}
在我的排序函式中,我想分配 stringComp 或 intComp 函式:
template<typename T>
void sort(std::vector<T>& vector)
{
bool (*compare)(T a, T b);
if (typeid(T) == typeid(int))
{
compare = &intComp;
}
else if (typeid(T) == typeid(std::string))
{
compare = &stringComp;
}
...
}
當我洗掉 else if 塊時,分配和排序作業正常compare = &stringComp
。但是,一旦我嘗試分配型別不是int
(例如字串)的函式,我就會收到以下編譯器錯誤:'=': cannot convert from 'bool (__cdecl *)(std::string,std::string)' to 'bool (__cdecl *)(T,T)'
我做錯了什么?為什么代碼可以與 int 一起使用,但不能與其他型別一起使用?模板是否可以在引擎蓋下使用類似于列舉的整數,這就是為什么我可以毫無問題地分配 intComp 函式?
uj5u.com熱心網友回復:
問題是正常的所有分支都if
需要在編譯時有效,但您的分支中只有一個是有效的。如果T
是int
,則compare = &stringComp
無效。如果T
是std::string
,則compare = &intComp
無效。
相反,您需要if constexpr
,它是在 C 17 中引入的,并在編譯時進行比較。只要它依賴于模板引數,它就會丟棄不需要的分支,因此它們是否對該型別沒有意義并不重要。例如:
template <typename T>
void sort(std::vector<T>& vector)
{
bool (*compare)(T a, T b);
if constexpr (std::is_same_v<T, int>) {
compare = &intComp;
} else if constexpr (std::is_same_v<T, std::string>) {
compare = &stringComp;
} else {
// Error
}
// ...
}
uj5u.com熱心網友回復:
在 C 17 中,您可以在以下情況下使用 constexpr:
#include <string>
#include <vector>
#include <typeinfo>
bool intComp(int a, int b) { return a < b; }
bool stringComp(std::string a, std::string b) { return a < b; }
template<typename T>
void sort(std::vector<T>& vector)
{
bool (*compare)(T a, T b);
if constexpr (typeid(T) == typeid(int))
{
compare = &intComp;
}
else if (typeid(T) == typeid(std::string))
{
compare = &stringComp;
}
}
之前,我實際上會在 C 17 及更高版本中使用它,您可以讓多載決議選擇正確的函式:
#include <string>
#include <vector>
#include <iostream>
bool Comp(int a, int b) { return a < b; }
bool Comp(std::string a, std::string b) { return a < b; }
template<typename T>
void sort(std::vector<T>& vector)
{
if (vector.size() > 1) {
std::cout << Comp(vector[0],vector[1]);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473699.html
上一篇:如何讓模板函式接受任何你可以構造一些basic_string_view的東西
下一篇:為什么在模塊中匯出型別別名(例如std::vector<std::string>)允許在某些內部磁區中同時使用std::vector和std::string?