加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用模板特化,默认参数和VS2013编译错误

发布时间:2020-12-16 07:07:13 所属栏目:百科 来源:网络整理
导读:templatetypename Tvoid f(const T v = T());templatevoid fstd::string(const std::string v){ std::cout v;}int main(int argc,char* argv[]){ fstd::string(); // Error in VS2013,OK in VS2012,gcc-4.7 fstd::string("Test"); // OK fstd::string(std::s
template<typename T>
void f(const T &v = T());

template<>
void f<std::string>(const std::string &v)
{
    std::cout << v;
}

int main(int argc,char* argv[])
{
    f<std::string>(); // Error in VS2013,OK in VS2012,gcc-4.7
    f<std::string>("Test");   // OK
    f<std::string>(std::string());  //OK
    return 0;
}

最新的Visual Studio 2013编译器在必须使用默认参数的情况下给出以下编译器错误:

error C2440: 'default argument' : cannot convert from 'const std::string *' to 'const std::string &'
Reason: cannot convert from 'const std::string *' to 'const std::string'
No constructor could take the source type,or constructor overload resolution was ambiguous

Visual Studio 2012和gcc-4.7编译正常.

更新:因为它似乎是一个VS2013错误,是否有任何临时解决方法,在MS修复此问题之前不需要进行大量代码更改?错误报告已在MS connect上提交.

解决方法

每当我看到模板功能出现这种问题时,我都会尝试切换到模板结构(如果需要临时解决方法)……

template<typename T>
struct foo
{
  static void f(const T &v = T());
};

template<>
struct foo<std::string>
{
  static void f(const std::string &v = std::string())
  {
    std::cout << v;
  }
};

不幸的是,我无法在Visual Studio 2013中检查这个,因为我没有它,但我希望它应该工作.

这里的缺点是你应该明确指定你的类型,它不再被扣除

foo<std::string>::f()
foo<std::string>::f("Text")

我在这里的猜测是添加像包装函数:

template<typename T>
void f_wrapper(const T &v = T())
{
  foo<T>::f(v);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读