簡體   English   中英

C++ std::enable_if

[英]c++ std::enable_if

我對 std::enable_if 很陌生,想知道如何使用它。 我有一個模板類:

template<int a, int b>
class foo {
}

現在我只想在 a + b 等於 10 時實例化它。我可以使用 std::enable_if 使這成為可能嗎?

第二個問題:如果我在 foo 類中有一個成員

template<int a, int b>
class foo {
  int c;
}

我只想有 c 的時候

a = 5. 

我如何使用 std::enable_if 做到這一點? 這是使用 std::enable_if 的正確情況嗎?

template<int a, int b, typename T = typename std::enable_if<a + b == 10>::type>
class foo {
};

這應該可以完成工作; 只需確保在實例化模板時永遠不會顯式提供第三個模板參數。


正如其他人提到的, static_assert更適合。

我猜你可以更好地使用 static_assert 來強制執行該約束而不是 enable_if

template<int a, int b>
class foo {
    static_assert(a+b==10, "a+b is not 10");
};

int main()
{
    foo<5,5> f; // will compile
    foo<1,5> f; // will fail to compile with error: a+b is not 10
    return 0;
}

enable_if 主要用於根據類型特征有條件地從重載決議中刪除函數和類,並為不同的類型特征提供單獨的函數重載和特化。

使用 C++20

requires在模板中添加 require 即可實現:

template<int a, int b> requires (a + b == 10)
struct foo {
    int c;
};

int main() {
    foo<3, 7> ok;
    // foo<3, 8> doesnt_compile;
}

requires子句獲得一個constant expression ,該表達式的計算結果為truefalse ,如果 requires 子句為真,則決定是否將其視為正確匹配,否則忽略它。

代碼: https ://godbolt.org/z/yHh4Et

很簡單,就是不要使用enable_if

template<bool Ten>
struct Base
{
    int c;
};

template<>
struct Base<false>
{ };

template<int a, int b>
struct foo : Base<a+b == 10>
{
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM