是否可以调用模板化的强制转换操作符显式指定模板参数?

W.F*_*.F. 5 c++ templates operator-overloading c++11

考虑一下代码:

#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)};
}
Run Code Online (Sandbox Code Playgroud)

现在我可以使用from_string如下函数:

string s = "123";
int x = from_string(s);
cout << x << endl;
Run Code Online (Sandbox Code Playgroud)

我只是好奇是否有办法调用converterstruct 的强制转换操作符显式指定模板参数.语法:

from_string(s).operator int<int, converter_impl<int>>();
Run Code Online (Sandbox Code Playgroud)

不起作用......

use*_*083 1

您可以调用强制转换运算符,因为它不是模板化的:

int x = from_string(s).operator int();
Run Code Online (Sandbox Code Playgroud)

或者像这样

int x = from_string(s).template operator int();
Run Code Online (Sandbox Code Playgroud)

作为显式指定第二个模板参数的解决方法:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

auto y = from_string(s).cast<int, converter_impl<int> >();
Run Code Online (Sandbox Code Playgroud)