此處的示例顯示了我們如何使用 TMP 讓編譯器根據給定型別的成員是否存在來洗掉函式。我想撰寫一個適用于基于模板的類的元函式。如果在具有所需成員的函式呼叫中提供了基于模板的類,則編譯應該會成功。
班上:
template <typename KeyType>
struct RawBytesEntry
{
bool used = false;
size_t psl = 0;
KeyType key;
...
}
我嘗試了一系列不同的建議和語法排列,但我無法讓它發揮作用。有沒有人有什么建議?這是我認為我得到的“最接近”的東西:
template <template <typename> typename EntryType, typename = void>
struct has_psl : std::false_type
{
};
template <template <typename KeyType> typename EntryType>
struct has_psl<EntryType<KeyType>, std::void_t<decltype(EntryType<KeyType>::psl)>> : std::true_type
{
};
template <template <typename KeyType> typename EntryType, std::enable_if<has_psl<EntryType>::value>>
bool f(EntryType<KeyType> *buffer, size_t offset, EntryType<KeyType> *new_entry)
uj5u.com熱心網友回復:
模板模板引數的模板引數s不能在body中使用。
template <typename T, typename = void>
struct has_psl : std::false_type
{};
template <template <typename> typename EntryType, typename KeyType>
struct has_psl<EntryType<KeyType>, std::void_t<decltype(EntryType<KeyType>::psl)>> : std::true_type
{};
template <template <typename> typename EntryType, typename KeyType, std::enable_if<has_psl<EntryType<KeyType>>::value>>
bool f(EntryType<KeyType> *buffer, size_t offset, EntryType<KeyType> *new_entry) {
return true;
}
接著,
static_assert(has_psl<int>::value == false);
static_assert(has_psl<RawBytesEntry<int>>::value == true);
在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/496360.html
上一篇:使用模板在C 中實作訪問者模式
