c++ - illegal user defined conversion? -


here code , comment:

template<class t> struct b {     b(){}      template<class t1> operator t1() { return t1(); }      // define macro if compiler fails. #if (defined use_more_tidous_way) // (defined _msc_ver)     template<class t1> explicit b(b<t1> const& ) {}     template<class t1> operator b<t1>() { return b<t1>(); } #else     template<class t1> b(b<t1> const& ) {} #endif   #if 0     ////// explanation:      // firstly, want have convserion ctor :     template<class t1> b(b<t1> const& ) {}      // , conversion function :     template<class t1> operator t1() { return t1(); }      // may t1 general, hide above     // conversion ctor compilers (msvc8~10 fail, gcc 4.4.0~ ok)      // overcome such case, add conversion function :     template<class t1> operator b<t1>() { return b<t1>(); }      // , not use conversion ctor, while can still have ctor upon b<t1>     template<class t1> explicit b(b<t1> const& ) {}  #endif };   // test cases  template<class t> void func(t const&){};  void test() {     typedef b<int>      b1;     typedef b<float>    b2;       b1 b1;     b2 b2 = b1; // b1 => b2     b1 = b2;    // b2 => b1     b2 = b1;    // b1 => b2     func<b1>(b2);   // b2 => b1     func<b2>(b1);   // b1 => b2 }  int main() {     test(); } 

so, conversion more standard conformed , preferred?

the problem conversion:

template<class t1> operator t1() { return t1(); } 

is convert b anything, these compile:

typedef b<int>      b1; typedef b<float>    b2;   b1 b1; b2 b2 = b1; // b1 => b2 int x = b1; // compiles std::string s = b2; // compiles 

looking @ test case, these examples require assignment operator not copy constructor:

b1 = b2;    // b2 => b1 b2 = b1;    // b1 => b2 

so if define class assignment operators this, test cases should work:

template<class t> struct b {     b(){}     b& operator=(b&){ return b<t>();};      template<class t1> b(b<t1> const& ) {}     template<class t1> b& operator=(b<t1>&){return b<t>();};  }; 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -