[英]c++ template meta programming: how do you define the type trait "is_xxxxx_v" alias for my custom trait?
所以我一直在看這個: https://akrzemi1.wordpress.com/2017/12/02/your-own-type-predicate/
它表明您可以采用自定義特征(或謂詞) is_thing<T>::type
並將其別名為is_thing_t<T>
- 例如:
template <bool Cond>
using enable_if_t = typename enable_if<Cond>::type;
現在我想做同樣的技巧來實現其他特征中使用的值別名。 我的嘗試下面有一段代碼:
// Primary template
// tparam 1 (T) is to pass in the class-under-test.
// tparam 2 (deafult to void) is to catch all cases not specialised - so they evaluate to false
template <typename T, typename = void>
struct is_really_bob : std::false_type {};
// specialisation
// tparam 1 (T) is to pass in the class-under-test.
// tparam 2 special meta-function that - if our class best-matches THIS template then it will evaluate to true
template <typename T>
struct is_really_bob <T, std::void_t<
typename T::result_type, // Has a nested type called result_type
decltype(T::check_bob()), // Has a static member fn called check_bob
decltype(std::is_default_constructible_v<T>), // required for below:
decltype(T{}.set_bob(std::string{""})), // has member fn set_bob that takes a string (also requires default c'tor)
decltype(T{}.get_bob()) // has member fn get_bob (also requires default c'tor)
>> : std::true_type {};
///// THIS FAILS /////
template <bool T>
using is_really_bob_v = typename is_really_bob<T>::value;
這里的問題是::value
不是類型名稱。 我不知道生成值別名的語法。 有沒有辦法做到這一點? 我希望最終能夠執行以下操作:
if constexpr (is_really_bob_v<T>)
{
// ...
}
完整的代碼示例在這里: https://godbolt.org/z/dG11vxesW - 沒有嘗試 at::value 別名注釋掉所以我們至少可以看到代碼工作的 rest
您對is_really_bob_v
的定義有兩個問題:
template <bool T>
而模板需要一個類型。它應該是
template <typename T>
// ^^^^^^^^ not bool
inline constexpr bool is_really_bob_v = is_really_bob<T>::value;
//^^^^^^^^^^^^^^^^^^^no type alias ^ no typename
使用我上面的更正,以下工作按預期工作:
struct BobTest {
BobTest() = default;
using result_type = bool;
void set_bob(std::string) {}
std::string get_bob() { return "bob"; }
static void check_bob() {}
};
struct NonBobTest {
NonBobTest() = default;
// using result_type = bool;
void set_bob(std::string) {}
std::string get_bob() { return "bob"; }
static void check_bob() {}
};
int main() {
std::cout << "Is BobTest a real bob? " << is_really_bob_v<BobTest> << "\n";
std::cout << "Is NonBobTest a real bob? "
<< is_really_bob_v<NonBobTest> << "\n";
}
Output:
Is BobTest a real bob? 1
Is NonBobTest a real bob? 0
由於 C++14 您可以將變量模板聲明為:
template <typename T>
inline constexpr bool is_really_bob_v = is_really_bob<T>::value;
Before C++14, you can declare it as static data members of a class template, or as return value of a constexpr function template.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.