How to reference a bi-directional free function in C ++

I have a template class in which I define free functions that reference this template class. These free functions are also templated by another parameter.

Outside the class, I can name free functions. However, I cannot find the correct syntax for one free function to call another.

Quick example:

template<typename T> class Foo { template<typename S> friend S f(const Foo &) { return S(); } template<typename S> friend S g(const Foo &s) { return f(s); // See below, when instantiated, yields 'no matching function for call to f(const Foo &)' } }; float test1() { Foo<int> o; return f<float>(o); // Compiles } float test2() { Foo<int> o; return g<float>(o); // Fails to compile as line above errors } 

(cf this link )

It seems that the f (s) call point inside g (), the external pattern has been lost. How can I re-specify T in a call to f? I checked on GCC4.7, 4.8, clang 3.2 all with equivalent errors.

+4
source share
1 answer

When you call f(s) , you need to specify the template parameter S , because it cannot be inferred from the argument S

But if you change it to f<S>(s) (assuming that you intended to call it with the same argument of the S template that g was called from), you forbid ADL and the only way to define a friend function in the region class can be found ADL. Therefore, you need to add the declaration of f to the global namespace so that a call to g can find it.

So, to make it work, you need to add these declarations before Foo

 template<typename T> class Foo; template<typename S, typename T> S f(const Foo<T> &); template<typename S, typename T> S g(const Foo<T> &); 

and change the call in g to f<S>(s) or something else like f<x>(s)

+6
source

Source: https://habr.com/ru/post/1481980/


All Articles