Link crashes and const

Consider this program:

template<typename T>
struct Foo
{
    void foo(const T&) {}   
    void foo(T&) {}
};


int main()
{
    Foo<double&> f;   
    double d = 3.14;
    f.foo(d);   //complains that foo() is ambigous
}

      

In the above example, if Foo is instantiated like Foo<double>

, then everything is fine, but if it is instantiated like Foo<double&>

, then the call foo

becomes ambiguous. The ref collapses when playing here when inferring parameter types for foo

, and if so why ignoring the constant?

+3


source to share


1 answer


Let's see what happens if we try to set a class template Foo

:

template<typename T>
struct Foo {
  void foo(T const&) {}   
  void foo(T&) {}
};

      

with a template parameter double&

. Substituting T in double&

and following the link dropping rules, you get:

struct Foo {
  void foo(double& const) {}   
  void foo(double&) {}
};

      

Since the links are essentially permanent, is double& const

equivalent double&

. This way you get the next generation:



struct Foo {
  void foo(double&) {}   
  void foo(double&) {}
};

      

Here's a compiler screaming, "Dude, you can't overload with Foo

the same signature."

A more complex error is given by CLANG:

error: multiple overloads of 'foo' create the same signature 'void (double & &)' void foo (T &) {}

Live Demo

+3


source







All Articles