如何确保迭代器模板形参与模板类的模板形参具有相同的数据类型
How to make sure an iterator template parameter has the same data type as the template parameter of a template class
不好意思,标题太长了…请让我知道如何做得更好。
我有一个模板类:template <typename T>
class Example {
...
template <typename Iterator>
void add(const Iterator begin, const Iterator end);
...
};
如何确保Iterator
所指向的数据类型是T
另一个相关问题:
STL vector构造函数
template <class InputIterator>
vector (InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type());
确保InputIterator
具有兼容的数据类型作为向量?
是否有一个编译时的解决方案?
您可以这样做:
template <typename Iterator>
void add(const Iterator begin, const Iterator end)
{
static_assert(std::is_same<typename std::iterator_traits<Iterator>::value_type,
T>::value, "Iterator must be the same as T");
}
这样做可以确保Iterator所指向的数据类型为T:
template <typename T>
class Example
{
public:
void add(const T* begin, const T* end)
{
}
};
vector构造函数不确保InputIterator具有与vector兼容的数据类型。它只是分配内存和分配元素。因此,如果InputIterator所指向的数据类型可以隐式地转换为vector类型,则编译成功,这并不能保证正确的赋值行为。否则会报告错误。
char a[3] = {1, 2, 3};
vector<int> ivec(a, a + 2);
可以成功编译。
string str[3] = {"a", "b", "c"};
vector<int> ivec(str, str + 2);
这并不.
相关文章:
- 非类型引用形参/实参
- 如何确保迭代器模板形参与模板类的模板形参具有相同的数据类型
- 如何在编译时通过模板形参默认值的名称/指针获取函数的类型
- 模板类的不同返回类型取决于类的形参
- 指向函数的指针vs作为模板非类型形参的函数
- 具有不同值类型模板形参的模板类的数组或向量
- 为什么模板非类型形参指针和引用实参需要是全局的
- 可以使用MemberFunction类型作为模板形参吗?
- c++ 03:是否有一种方法可以使一个类型每次被包含在模板形参中时都会编译成不同的类型?
- 将非const引用使用auto-keyword声明的lambda作为实参传递给std::函数形参类型
- 为什么标准不允许在模板形参列表中初始化依赖于常量的类型
- 在模板演绎中保持函数指针形参的完整类型
- 使用传入的字符串形参来访问类型中的内容
- 不能在模板专门化定义中将一个类的成员类型定义用作模板形参
- 传递给构造函数的形参不是类型
- 使用函数返回值作为默认模板非类型形参
- 扩展非类型形参包来定义带有非类型形参的内部类模板是否合法?
- 函数指针的形参类型的模板实参演绎涉及未演绎的形参包
- 如何正确声明以函数类型作为形参的模板(如std::function)
- c++模板非类型形参的类型演绎