Class template supporting function template

I get a linker error when I try to create an executable from the following code. I get the impression that I need to post some " typename s" or make some advanced announcements; I tried several combinations, but no one worked.

 template<typename T> class enabled { private: T type_; friend const T& typeof(const enabled<T>& obj); // Offending line }; template<typename T> const T& typeof(const enabled<T>& obj) { return obj.type_; } int main() { enabled<std::string> en; std::cout << typeof(en); std::cin.clear(), std::cin.get(); return 0; } 

1> main.obj: error LNK2001: unresolved external character "class std :: string const & __cdecl typeof (class included <class std :: string> const &)"

+6
source share
2 answers

Forwarding and determining that a function is templated

 template<typename T> class enabled; template<typename T> const T& typeof(const enabled<T>& obj) { return obj.type_; } template<typename T> class enabled { private: T type_; friend const T& typeof<>(const enabled<T>& obj); }; 
+4
source

The problem is that a function that is a friend of the class is not a function template, and the function that you actually defined is a function template.

All you have to do is make the function template for your friend as follows:

 template<typename T> class enabled { private: T type_; template<typename U> //<-------------------------------note this friend const U& typeof_(const enabled<U>& obj); //use U }; 

Now this compiles just fine: http://www.ideone.com/VJnck

But it makes all instances of typeof_<U> friend of all instances of enabled<T> , which means that typeof_<int> is a friend of enabled<T> for all possible value of T and vice versa.

Thus, the best solution is to force the non-template function and define it inside the class as follows:

 template<typename T> class enabled { private: T type_; friend const T& typeof_(const enabled<T>& obj) { return obj.type_; } }; 

Demo: http://www.ideone.com/Rd7Yk

Please note that I replaced typeof with typeof_ , since GCC has an extension named typeof , and therefore it throws an error on ideone (since I cannot disable extensions).

+3
source

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


All Articles