c++ - Swap function for user-defined class never instantiated? -
the following reduced example of i'm stumbling across larger class i'm creating , attempting make swappable providing own non-member friend swap function.
#include <iostream> #include <utility> template<typename t> class wrapper { friend void swap(wrapper& a, wrapper& b); public: wrapper(t t) : value_(t) {} const t& operator*() const { return value_; } private: t value_; }; template<typename t> void swap(wrapper<t>& a, wrapper<t>& b) { using std::swap; swap(a.value_, b.value_); } int main() { wrapper<int> w1{5}, w2{10}; std::cout << *w1 << " " << *w2 << std::endl; swap(w1, w2); std::cout << *w1 << " " << *w2 << std::endl; } attempting compile small test program results in following linker error clang (apple llvm version 7.0.2, clang-700.1.81 on os x el capitan 10.11.3):
[~/development/c++_test][16:30:57]$ clang++ --std=c++11 -o swaptest swaptest.cc undefined symbols architecture x86_64: "swap(wrapper<int>&, wrapper<int>&)", referenced from: _main in swaptest-a978ea.o ld: symbol(s) not found architecture x86_64 clang: error: linker command failed exit code 1 (use -v see invocation) why template swap function wrapper class i've defined not instantiated appropriately despite use of in main()?
friend void swap(wrapper& a, wrapper& b); declares non-template function swap happens take wrapper<t>& arguments. doesn't match template function swap<t>.
one simple fix declare friend template function.
template <typename u> friend void swap(wrapper<u>&a, wrapper<u>& b); the drawback there you've friended little more wanted: every swap instantiation friend of every wrapper<t>, not correct wrapper<t> class.
a more correct way involves declaring template function before class:
template <class t> class wrapper; template <class t> void swap(wrapper<t>&, wrapper<t>&); template <class t> class wrapper { friend void swap<>(wrapper&, wrapper&); // ...
Comments
Post a Comment