C ++ frontend interface and templates

In C ++, we can omit the qualification of the namespace if we use a function that takes as its first argument an object of the type declared in the same namespace as our function. However, I noticed that this does not work with function templates (e.g. std :: get). I wrote a simple example to confirm that this is really related to patterns:

namespace ns { struct S {}; void sFoo(const S&) {} template<typename T> void sBar(const S&) {} } void foo() { ns::S s; sFoo(s); // ok sBar<int>(s); // error: 'sBar' was not declared in this scope ns::sBar<int>(s); // ok } 

I tried explicitly creating the instance, but didn't change anything (even if it were, it would be a worse option than just using).

So, why can't I name a template function without specifying its namespace (and assuming neither using nor using namespace directives)?

+4
source share
1 answer

sBar not a function, but a function template. Argument-dependent searches work only for function names. It is true that sBar<int> is a function, but you cannot create an instance of a template unless you know its own name!

Unbound, if the template argument can be inferred, this ADL works:

 namespace ns { template <typename T> void sZip(T &) { } } void foo() { ns::S s; sZip(s); // OK, deduces T = ns::S } 

The general "best practice" for C ++ is to create function templates only if the arguments can be inferred and never specify the arguments explicitly. (The exceptions to this rule are std::forward and various make_* functions, which require one required argument for the desired type of result.)

+2
source

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


All Articles