Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call the templated cast operator explicitly specifying 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 e.g. use the from_string function as follows:

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

I am just curious if there is a way to call the cast operator of converter struct explicitly specifying the template parameters. The syntax:

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

does not work...

like image 579
W.F. Avatar asked Nov 08 '22 15:11

W.F.


1 Answers

You can call cast operator either as it is not templated:

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

or like this

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

As workaround to specify 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 like this:

auto y = from_string(s).cast<int, converter_impl<int> >();
like image 108
user2807083 Avatar answered Nov 14 '22 23:11

user2807083