How to directly call a conversion operator?

struct Bob { template<class T> void operator () () const { T t; } template<class T> operator T () const { T t; return t; } }; 

I can directly call the Bob () operator as follows

 Bob b; b.operator()<int>(); 

How to directly invoke a conversion operator with a specific template parameter like this?

 Bob b; std::string s = b.???<std::string>(); 

Unable to use static_cast

 Bob b; std::string s = static_cast<std::string>(b); 

http://ideone.com/FoBKp7

error: call of overloaded 'basic_string(Bob&)' is ambiguous

Question How to directly handle the template parameter OR this is not possible. I know that there are workarounds using the wrap function.

+4
source share
2 answers

You can call it directly (explicitly) as follows:

 Bob b; std::string s = b.operator std::string(); 

but it is not "with a specific template parameter" (but there is no need).

See also Comment WhozCraig

+7
source

Use the helper function:

 template< typename T > T explicit_cast( T t ) { return t; } int main() { Bob b; std::string s = explicit_cast<std::string>(b); } 
+3
source

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


All Articles