Fra*_*ido 5 c++ constructor iterator sfinae c++14
我想为某个对象实现一个范围构造函数,但我想将它限制为只接受两个输入迭代器.
我试图用gcc 7.1.0编译这段代码.
文件 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());
}
Run Code Online (Sandbox Code Playgroud)
我得到这个编译错误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
Run Code Online (Sandbox Code Playgroud)
我决定使用默认模板参数,因为它更适合构造函数.操作符的使用typeid()是因为我发现在保存代码时它很容易阅读,但我不能让它以任何方式工作.
其他解决方案看起来非常奇怪并且非常模糊(比如强制InputIterator参数使用某些方法,例如*it或++).如果我无法做到这一点,我会很感激,或多或少,易于阅读的解决方案.
为了执行 SFINAE,您需要确保涉及表达式的求值发生在编译时。对于typeid以下情况适用:
当应用于多态类型的表达式时,typeid 表达式的求值可能涉及运行时开销(虚拟表查找),否则 typeid 表达式在编译时解析。
因此,我不会考虑typeid静态(编译时)多态性的好选择。
解决问题的一种方法是将标签调度与委托构造函数结合使用,如下所示:
template <typename T>
class A{
std::vector<T> v;
template <typename InputIterator>
A(InputIterator first, InputIterator last, std::input_iterator_tag) : v(first, last) {}
public:
template<typename InputIterator> A(InputIterator first, InputIterator last)
: A(first, last, typename std::iterator_traits<InputIterator>::iterator_category()) {}
};
Run Code Online (Sandbox Code Playgroud)