Is it possible to call a template operator-operator that explicitly sets the template parameters?

Consider the code:

#include <string> #include <sstream> template <class T> struct converter_impl { std::string to_convert; operator T() { T result; std::stringstream ss(to_convert); ss >> result; return result; } }; struct converter { std::string to_convert; template <class T, class CI = converter_impl<T>> operator T() { CI ci = CI{std::move(to_convert)}; return ci; } }; converter from_string(std::string s) { return converter{std::move(s)}; } 

Now I can, for example. use the from_string function as follows:

 string s = "123"; int x = from_string(s); cout << x << endl; 

I'm just wondering if there is a way to invoke the listing operator of the converter structure that explicitly sets the template parameters. Syntax:

 from_string(s).operator int<int, converter_impl<int>>(); 

does not work...

+5
source share
1 answer

You can call the translation operator either if it was not a template:

 int x = from_string(s).operator int(); 

or how is it

 int x = from_string(s).template operator int(); 

As a workaround to specify the second template parameter explicitly:

 struct converter { std::string to_convert; template <class T, class CI > operator T() { CI ci = CI{std::move(to_convert)}; return ci; } template <class T, class CI> T cast() { CI ci = CI{std::move(to_convert)}; return ci; } }; 

and use it as follows:

 auto y = from_string(s).cast<int, converter_impl<int> >(); 
+1
source

All Articles