首页 \ 问答 \ 有没有办法确保在C ++中传递的模板参数是一个迭代器?(Is there a way of ensuring the template argument passed in C++ is an iterator?)

有没有办法确保在C ++中传递的模板参数是一个迭代器?(Is there a way of ensuring the template argument passed in C++ is an iterator?)

在C ++中,我正在实现vector类,并在使用任何类型作为T的参数时遇到错误:

void insert(iterator where, size_type count, const_reference value = T()){...}

template <typename InIt>
void insert(iterator where, InIt first, InIt last){...}

在执行以下操作时:

vector<int> v;
for (int i = 0; i < 5; ++i)
{
    v.push_back(i + 1);
}
v.insert(v.begin() + 2, 10, 8);
v.insert(v.begin() + 4, 9);

它将InIt的参数作为int ,它实际上应该是一个iterator类型的类,并且意味着调用了错误的函数,导致内部内存错误。 因此,我不得不使用template <typename InIt>参数来移除insert函数,因为它破坏了我的实现。 我已经试过这与std::string并发生同样的问题。

我能做些什么来区分这两个功能?


In C++, I am making an implementation of the vector class and came across an error when using any type as the argument for T:

void insert(iterator where, size_type count, const_reference value = T()){...}

template <typename InIt>
void insert(iterator where, InIt first, InIt last){...}

When doing the following:

vector<int> v;
for (int i = 0; i < 5; ++i)
{
    v.push_back(i + 1);
}
v.insert(v.begin() + 2, 10, 8);
v.insert(v.begin() + 4, 9);

It takes the argument for InIt as int, when it should in fact be an iterator type class and means that the wrong function is called, resulting in internal memory errors. As a result, I have had to remove the insert function with the template <typename InIt> argument as it ruins my implementation. I have tried this with std::string and the same problem occurs.

Is there anything I can do to differentiate these two functions?


原文:https://stackoverflow.com/questions/31123289
更新时间:2019-09-10 23:17

最满意答案

这就是SFINAE的用途 - 如果InIt不是看起来像迭代器的东西,那么从重载集合中删除第二个重载。 在这种情况下,您只需要一个输入迭代器,它必须既可以递增又可以取消引用:

template <typename InIt,
          typename = decltype(*std::declval<InIt&>(),
                              ++std::declval<InIt&>())>
void insert(iterator where, InIt first, InIt last)
{
    ...
}

如果你想用一些整型来调用insert (这样它可以转换为size_t ), *std::declval<InIt&>将是一个无效的表达式,因为整型不可忽略 - 所以模板扣除将失败。 因为我们不会考虑这个超载,所以我们不会考虑这个超载,而是第一个被调用。


This is what SFINAE is for - remove the 2nd overload from the overload set if InIt is not something that looks like an iterator. In this case, you just want an input iterator, which has to be both incrementable and dereferencable:

template <typename InIt,
          typename = decltype(*std::declval<InIt&>(),
                              ++std::declval<InIt&>())>
void insert(iterator where, InIt first, InIt last)
{
    ...
}

If you were to call insert with some integral type (so that it can be converted to size_t), *std::declval<InIt&> would be an invalid expression since integral types aren't dereferencable - so template deduction would fail. Because Substitution Failure Is Not An Error, the effect is that this overload is removed from consideration, and the first one would be called instead.

2015-06-29

相关问答

更多

相邻的JSX元素必须封装在封闭标签中(Adjacent JSX elements must be wrapped in an enclosing tag)

当你将它包装在一个视图中时,确保你将flex设置为1.我的猜测是你给它的视图没有大小,因此子元素从父元素继承它们的大小(这是0) When you wrap it in a view make sure you set the flex to 1. My guess is that the view you are giving it has no size and therefore the child elements are inheriting their size from the p

下载maven依赖项时校验和验证失败(Checksum validation failed while downloading maven dependency)

我只是手动下载了JAR文件,校验和是正确的。 您的互联网连接存在问题。 可能是破损的电缆,接口,路由器等,或者是香蕉的防火墙/防病毒软件。 I've just manually downloaded the JAR file and the checksum is the correct one. There is a problem with your internet connection. Probably a broken cable, interface, router, etc.,

如何在swagger-maven-plugin 3.1.0中设置覆盖模型(How to set overriding models in swagger-maven-plugin 3.1.0)

以下是我最终解决问题的方法(我使用的是swagger-maven-plugin 3.1.1版): 假设您要将java.util.Date映射为此任意结构: { "year": "string", "month": "string", "day": "string" } 第1步:创建一个描述上述模型的类: package com.example; import io.swagger.annotations.ApiModel; import io.swagger.annotation

图像放大 - 限制小图像(Image upscaling - limit for small images)

如果您的意思是想要将图像太宽到100%,而只留下较小的图像,则必须写入max-width:100%而不是width:100% 。 无需为较小的图像提供特殊类。 If you mean you want to scale images that are too wide down to 100%, while leaving smaller images alone, you will have to write max-width:100% instead of width:100%. No n

选择第一个选择标签后,在第二个选择标签中给出子类别(Give subcategories in second select label after selecting first select label)

我没有测试代码,但我认为这应该工作。 而不是通过ajax只获取选项,像这样获取整个选择框。 所以你的ajax.php将会是 - <?php if(isset($_POST['get_option'])) { $p_id = $_POST['get_option']; $query = "SELECT * FROM categories WHERE parent_id ='$p_id'"; $ch_cat = $db->select($query);

如何直接调用Facebook和Vk的分享方法(How to call share method of Facebook and Vk directly)

对于Facebook我知道只与这个Facebook提要对话共享 https://developers.facebook.com/docs/android/share 要么 使用此代码的浏览器 Session.openActiveSession(this, true, new Session.StatusCallback() { @Override public void call(Session session, SessionState state,

MySQL存储过程调用列表(MySQL Stored Procedure Call With List)

给这个镜头: DELIMITER $$ drop procedure if exists doSomething1234$$ CREATE PROCEDURE doSomething1234 (IN id_list TEXT) BEGIN -- note id_list is passed in like a string '1,2,3,7' -- it will be wrapped for the in clause like in (1,2,3,7) --

C常量(C Constants)

你很可能希望你的定义是这样的: #define MONTHS 12 /* some code here... */ int payAnnual = payMonthly * MONTHS; 要回答你的问题,将不会使用内存。 预处理器不了解变量和内存等概念。 它本质上是一个自动文本编辑器。 它将用12取代任何符号MONTHS。 由于预处理器非常笨,所以通常最好使用const变量。 这为您提供了类型检查的好处,并且可以使编译器错误更容易阅读。 只要你声明它是静态的,变量就会被优化掉。 (如果你

相关文章

更多

最新问答

更多
  • asp.net任意用户信息(asp.net arbitrary user info)
  • 如何使用python计算docx文件中表中行的值(How to count the row's values in tables in docx file by using python)
  • MySQL:用户访问和数据库覆盖(MySQL: User access and DB overwriting)
  • 还有另一种“使用未分配的局部变量”的问题(Yet Another “Use of unassigned local variable 'whatever' ” question)
  • 开源证书颁发机构软件(Open source certificate authority software)
  • Rails中的迭代form_for是在create上添加模型的所有实例(Iteration in Rails form_for is adding all instances of model on create)
  • 如何扩展我的表视图单元格?(How to expand my table view cell?)
  • 如何使用SPARQL区分Thing和无生命对象(How to differentiate between a Thing and an inanimate object with SPARQL)
  • 在IdentityServer中,Client Secrets和Scope Secrets有什么区别?(In IdentityServer, what is the difference between Client Secrets and Scope Secrets?)
  • 如何在具有附加类时重写类(How do I override a class when it has a attached class)
  • 如何使用Git在Azure上部署C#,MVC4应用程序(How to deploy a C#, MVC4 application on Azure using Git)
  • Sitecore 7内容搜索爬网程序根目录之外的索引项(Sitecore 7 Content Search indexing items outside of crawler root)
  • 我应该在线课程使用utf-8编码吗?(Should I use utf-8 encoding for an online course?)
  • 如何在Cucumber-JS步骤定义中使用Node-mysql连接到MySQL?(How to connect to MySQL using Node-mysql in a Cucumber-JS step definition?)
  • 在MVC 4中的google.maps.LatLng(lat,lon)中将JSON字符串值分配给纬度和经度(Assign the JSON string value to Latitude and Longitude in google.maps.LatLng(lat,lon) in MVC 4)
  • awk:通过特定的分隔符删除字符串(awk: remove strings by specific delimiter)
  • 如何测试Vista的应用程序(How to test app for Vista)
  • Elasticsearch聚合器 - 缺失值的工作原理(Elasticsearch aggregators - How missing values work)
  • 绘制datetime.date熊猫(Plot datetime.date pandas)
  • PostgreSQL作为WSO2 EI和APIM + IS的数据源(PostgreSQL as datasource for WSO2 EI and APIM+IS)
  • 如何使用bash在postgres中运行alter table脚本(How to run alter table script in postgres using bash)
  • 可能使用PHP阻止整个美国州访问我的网站?(Might it be possible to block an entire US state from accessing my site, using PHP?)
  • restangular删除并输入错误网:: ERR_NAME_NOT_RESOLVED(restangular remove and put error net::ERR_NAME_NOT_RESOLVED)
  • 常见问题解答的Modx(Revolution)搜索功能(Modx(Revolution) search function for FAQs)
  • Rubymine如何使用远程口译员和Git?(How Does Rubymine Work With Remote Interpreters and Git?)
  • prepareForSegue和PerformSegueWithIdentifier发件人(prepareForSegue and PerformSegueWithIdentifier sender)
  • postgrsql与PowerShell无提示安装问题(postgresql silent installation issue with powershell)
  • 比较两个greps的输出(Comparing output from two greps)
  • 使用.NET RIA Data Services删除Silverlight 3中的数据(Deleting data in Silverlight 3 with .NET RIA Data Services)
  • 此行中AND运算符的含义(meaning of the AND operator in this line)