我遇到了一些麻烦,试图在Visual C++ 2010中实现一个智能相等测试宏类型模板函数,该函数与bug in VS in regard to default arguments of template functions有关。我通过在额外的函数中包含参数的值来修复它,但是现在我发现我不能在一行中使用两次函数!为什么在一行中使用这个C++函数两次会导致编译错误?
头文件
// example.h
#pragma once
#include <limits>
namespace myspace
{
// Need to define this separately to avoid a Visual Studio bug
template<typename T> T epsilon() { return std::numeric_limits<T>::epsilon(); }
// A generic equality test
template<typename T> inline bool smartEqual(
const T &v1,
const T &v2,
const T &eps = epsilon<T>())
{
return (v1 == v2);
}
// Template specialization for floating-point numbers
template<> bool smartEqual<float>(
const float &v1,
const float &v2,
const float &eps);
} // namespace myspace
源文件:
// example.cpp
#include "example.h"
using namespace std;
using namespace myspace;
// equal-macro specialization for floats using epsilon
template<> bool myspace::smartEqual<float>(
const float &v1,
const float &v2,
const float &eps)
{
return (fabs(v1 - v2) < eps);
}
int _tmain(int argc, _TCHAR* argv[])
{
float a,b;
bool x = smartEqual(a,b); // works ok
bool x = smartEqual(a,b) && smartEqual(b,a); // error
return 0;
}
如下报告错误:
------构建开始:项目:测试,配置:调试Win32 ------
test.cpp
c: (24):错误C2440:'默认参数':无法从'const float *'转换为'const float &'
原因是:\ n \ n \ ninja \不能从“常量浮动*”转换为“const的浮动”
没有上下文中,这种转换是可能
的违规行是一个,我尝试使用两倍的逻辑,并呼吁smartEqual() 。
我不明白为什么会发生这种情况。将“eps”从引用类型更改为简单的值类型可以修复它,但我希望我知道发生了什么。
谢谢!
如果实例'smartEqual <>()'2次,2种_different_类型,不会它会给你带有2个版本的'epsilon()',它们仅在返回类型上有所不同? – 2012-04-27 02:25:50
@Pavel:这确实也是一个有趣的问题,但是因为int ei = epsilon(); float ef = epsilon ();编译好吧,看起来他们在某种程度上是独立的功能。我的意思是,编译器以某种方式区分它们。不知道如何。 –
neuviemeporte
2012-04-27 02:32:59