我想使用 SFINAE 選擇要在具有非型別引數的模板類中編譯的特定函式,我是這樣做的:
#include<iostream>
#include<type_traits>
template <bool T>
struct is_right
{
template <class Q = std::bool_constant<T>>
typename std::enable_if<std::is_same<Q, std::bool_constant<true>>::value, bool>::type check()
{
return true;
}
template <class Q = std::bool_constant<!T>>
typename std::enable_if<std::is_same<Q, std::bool_constant<false>>::value, bool>::type check()
{
return false;
}
};
int main() {
is_right<false> is_fs;
is_right<true> is_ri;
if(!is_fs.check() && is_ri.check()){
std::cout << "It is right!" << std::endl;
}
return 0;
}
我使用 c 17 標準使用 g 8.1.0 編譯它。但是編譯器給了我一個錯誤,說“沒有匹配函式呼叫'is_right::check()'”。
但是,如果我只是用型別引數替換非型別模板引數,它可以作業:
#include<iostream>
#include<type_traits>
template <class T>
struct is_right
{
template <class Q = T>
typename std::enable_if<std::is_same<Q, std::bool_constant<true>>::value, bool>::type check()
{
return true;
}
template <class Q = T>
typename std::enable_if<std::is_same<Q, std::bool_constant<false>>::value, bool>::type check()
{
return false;
}
};
int main() {
is_right<std::bool_constant<false>> is_fs;
is_right<std::bool_constant<true>> is_ri;
if(!is_fs.check() && is_ri.check()){
std::cout << "It is right!" << std::endl;
}
return 0;
}
它們之間有本質區別嗎?
uj5u.com熱心網友回復:
第二個check函式的默認模板引數是錯誤的,應該是std::bool_constant<T>而不是std::bool_constant<!T>。
該呼叫is_fs.check()沒有匹配的函式,因為您正在is_same<bool_constant<false>, bool_constant<true>>第一次多載和is_same<bool_constant<true>, bool_constant<false>>第二次多載中進行測驗。
另請注意,現在呼叫is_ri.check()是模棱兩可的,因為這兩個check函式在is_right<true>.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434764.html
