![](/img/trans.png)
[英]c++ class constructor template with std::enable_if and std::decay
[英]C++ enable_if template class method if it is std::vector<std::vector<Type>>
我正在為接收std::vector
的結構實現flatten()
方法。
我希望僅當MyStruct
使用std::vector<std::vector<Type>>
構造時才使用flatten()
方法,而不是使用std::vector<Type>
構造(並且Type
不是std::vector
,當然)。
除了CLANG以外,它確實設法使其正常工作。 根據我的實現方式,我會得到不同的錯誤。
我想知道使用enable_if
執行此操作的正確方法。
我的結構的簽名應類似於以下內容:
template <typename Type>
struct MyStruct {
...
// this should only exist if Type is an std::vector
MyStruct<Type::value_type> flatten() {
...
}
}
為什么為此需要enable_if? 普通ol'型推導適合您:
template <typename T>
MyStruct<vector<T>> flatten(const MyStruct<vector<vector<T>>>& input) {
// ...
}
編輯:對於您的更新的問題,您真的很可能真的想在這里使用非成員。 對於您的客戶來說,這是一個更簡單的API,鑒於此功能,扁平化可能不需要訪問MyStruct的私有位,並且如果不需要訪問私有位,則應該是非成員非朋友。
如果出於某種原因要執行此操作,則可以使用一個自由函數為其編寫一個特征,然后在其中寫入static_assert,類似於:
http://melpon.org/wandbox/permlink/W0NG1VxX4fuia8kM
要么
http://melpon.org/wandbox/permlink/UJZ7qliuAqXLSW4b
#include <vector>
#include <type_traits>
template <typename T>
std::false_type is_vector_of_vector_helper(const T&); // not defined
template <typename T>
std::true_type is_vector_of_vector_helper(const std::vector<std::vector<T>>&);
template <typename T>
using is_vector_of_vector_t = decltype(is_vector_of_vector_helper(std::declval<T>()));
template <typename T>
struct MyStruct {
MyStruct<typename T::value_type> flatten() const {
static_assert(is_vector_of_vector_t<T>::value,
"Flatten should only be called with MyStruct<vector<vector<T>>>");
// impl
return {};
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.