【问题标题】:Compile error with template specialization, default arguments and VS2013使用模板特化、默认参数和 VS2013 编译错误
【发布时间】:2014-01-03 20:44:39
【问题描述】:
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 上提交。

【问题讨论】:

  • VS2013 拒绝这个是错误的。但是你的问题是什么?或者这只是一个咆哮?
  • 注意:std::cout &lt;&lt; v; 在 VS2012 中抛出错误:必须是 std::cout &lt;&lt; v.c_str();

标签: c++ templates visual-c++ visual-studio-2013


【解决方案1】:

每当我看到模板函数出现此类问题时,我都会尝试切换到模板结构(如果您需要临时解决方法)...

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);
}

【讨论】:

  • 感谢您的检查!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
相关资源
最近更新 更多