是否可以指定一個模板引數,它永遠不會匹配基本型別,例如 int?我正在與歧義作斗爭。例如:
template<class T> void Function(const T& x) { SetString(x.GetString()); };
僅當 T 中有 GetString 方法時才有效,但如果編譯器看到此函式,即使 T 只是 int ,它也會嘗試使用它。
uj5u.com熱心網友回復:
方法一
你可以使用std::enable_if如下圖:
C 11
//this function template will not be used with fundamental types
template<class T> typename std::enable_if<!std::is_fundamental<T>::value>::type Function(const T& x)
{
SetString(x.GetString());
};
演示
C 17
template<class T> typename std::enable_if_t<!std::is_fundamental_v<T>> Function(const T& x)
{
SetString(x.GetString());
};
演示
方法二
我們可以利用SFINAE。這里我們使用decltype和逗號運算子來定義函式模板的回傳型別。
//this function template will work if the class type has a const member function named GetString
template <typename T> auto Function (T const & x) -> decltype( x.GetString(), void())
{
SetString(x.GetString());
};
演示
在這里,我們使用尾隨回傳型別語法來指定函式模板的回傳型別。
uj5u.com熱心網友回復:
如果問題 iint不支持某個GetString()方法,則可能不是禁用基本型別的函式,而是在(且僅當)模板型別具有GetString() const接受不帶引數的呼叫的方法時啟用它。
注意GetString()一定是const,因為Function()接收到一個const參考,所以你只能GetString()在里面呼叫Function()ifGetString()是一個const方法。
下面是一個完整的編譯示例。觀察bar1和bar2案例中的失敗
#include <string>
void SetString (std::string const &)
{ }
struct foo // class with a conformat GetString method
{ std::string GetString () const { return "abc"; } };
struct bar1 // class with a not conformant (not const) GetString method
{ std::string GetString () { return "123"; } };
struct bar2 // class with a not conformant (require a int) GetString method
{ std::string GetString (int) const { return "123"; } };
struct bar3 // class without a GetString method
{ };
template <typename T>
auto Function (T const & x) -> decltype( x.GetString(), void())
{ SetString(x.GetString()); }
int main()
{
Function(foo{}); // compile
// Function(bar1{}); // compilation error (GetString isn't const)
// Function(bar2{}); // compilation error (GetString require a int)
// Function(bar3{}); // compilation error (no GetString method)
// Function(0); // compilation error (no GetString method)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438910.html
