Tôi muốn triển khai một hàm tạo phạm vi cho một đối tượng nhất định, nhưng tôi muốn hạn chế nó để chỉ chấp nhận hai trình lặp đầu vào.Làm thế nào để thực hiện một hàm tạo nên nó chỉ chấp nhận các trình lặp đầu vào bằng cách sử dụng typeid?
Tôi đã cố gắng biên dịch mã này bằng gcc 7.1.0.
file test.cpp
#include <vector>
#include <type_traits>
#include <typeinfo>
template <typename Iterator>
using traits = typename std::iterator_traits<Iterator>::iterator_category;
template <typename T>
class A{
private:
std::vector<T> v;
public:
template <typename InputIterator,
typename = std::enable_if_t<
typeid(traits<InputIterator>) ==
typeid(std::input_iterator_tag)>
>
A(InputIterator first, InputIterator last) : v(first, last) {}
};
int main(){
std::vector<double> v = {1, 2, 3, 4, 5};
A<double> a(v.begin(), v.end());
}
tôi nhận được lỗi biên dịch này với g++ test.cpp -o test
:
test.cpp: In function ‘int main()’:
test.cpp:27:34: error: no matching function for call to ‘A<double>::A(std::vector<double>::iterator, std::vector<double>::iterator)’
A<double> a(v.begin(), v.end());
^
test.cpp:22:7: note: candidate: template<class InputIterator, class> A<T>::A(InputIterator, InputIterator)
A(InputIterator first, InputIterator last) : v(first, last) {}
^
test.cpp:22:7: note: template argument deduction/substitution failed:
test.cpp: In substitution of ‘template<bool _Cond, class _Tp> using enable_if_t = typename std::enable_if::type [with bool _Cond = ((const std::type_info*)(& _ZTISt26random_access_iterator_tag))->std::type_info::operator==(_ZTISt18input_iterator_tag); _Tp = void]’:
test.cpp:18:16: required from here
test.cpp:19:49: error: call to non-constexpr function ‘bool std::type_info::operator==(const std::type_info&) const’
typeid(traits<InputIterator>) ==
test.cpp:18:16: note: in template argument for type ‘bool’
typename = std::enable_if_t<
^~~~~~~~
test.cpp:10:7: note: candidate: A<double>::A(const A<double>&)
class A{
^
test.cpp:10:7: note: candidate expects 1 argument, 2 provided
test.cpp:10:7: note: candidate: A<double>::A(A<double>&&)
test.cpp:10:7: note: candidate expects 1 argument, 2 provided
tôi quyết định sử dụng tham số mẫu mặc định vì là phù hợp hơn cho nhà xây dựng. Việc sử dụng toán tử typeid()
là vì tôi thấy nó dễ đọc khi đọc mã, nhưng tôi không thể làm nó hoạt động theo bất kỳ cách nào.
Các giải pháp khác trông rất lạ và thực sự mơ hồ (như buộc tham số InputIterator có các phương thức nhất định như * hoặC++). Nếu không có cách nào tôi có thể làm điều này, tôi sẽ đánh giá cao một, nhiều hơn hoặc ít hơn, dễ đọc giải pháp.
Tôi chưa bao giờ nghĩ đến ý tưởng này, điều này thực sự dễ hiểu và dễ thực hiện. Cảm ơn nhiều! –