Why does using this C++ function twice in one line cause a compile error?

不打扰是莪最后的温柔 提交于 2019-12-03 23:21:28

I think you've now hit this VS10 bug.

Your code compiles OK on VS11 Beta.

You could possibly avoid the default value (which seems to be a major issue for VS10) by changing smartEqual to:

template<typename T> inline bool smartEqual(
    const T &v1, 
    const T &v2)
{
    return (v1 == v2);
}

and simply specialising for float (and double) like this:

template<> bool myspace::smartEqual<float>(
    const float &v1, 
    const float &v2)
{
    return (fabs(v1 - v2) < std::numeric_limits<float>::epsilon());
}


Another option is to change the epsilon parameter to pass by value:

template<typename T> inline bool smartEqual(
    const T &v1, 
    const T &v2, 
    T eps = epsilon<T>())
{
    return (v1 == v2);
}

code failed in VS2010 but OK in Intel compiler. looks like a bug in VS2010

After some consideration, I've decided to go with a still another solution that @Fraser suggested (although I got the inspiration from him) and write my own answer:

  1. The first solution robs me of the flexibility of being able to use a custom value of eps.
  2. The second solution with the pass-by-value feels wrong, especially if in the future I will decide to use this function for some more contrived types.

Since VS seems overriden with bugs in regard to default values of parameters (only in templates?), it seems the most sensible thing to do is sidestep the issue by creating two versions of smartEqual; with and without the eps (using the default), which pretty much does the same thing, if not as concisely:

// An equality test that doesn't require the value of eps, default will be used
template<typename T> inline bool smartEqual(
    const T &v1, 
    const T &v2)
{
    return (v1 == v2);
}

// Float specialization: return (fabs(v1 - v2) < std::numeric_limits<float>::epsilon());
template<> inline bool smartEqual<float>(
    const float &v1, 
    const float &v2);

// A custom-eps value equality test
template<typename T> inline bool smartEqual(
    const T &v1, 
    const T &v2, 
    const T &eps)
{
    return (v1 == v2);
}

// Float specialization: return (fabs(v1 - v2) < eps);
template<> bool smartEqual<float>(
    const float &v1, 
    const float &v2, 
    const float &eps);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!