【问题标题】:Is it possible to call the templated cast operator explicitly specifying template parameters?是否可以调用模板化转换运算符显式指定模板参数?
【发布时间】:2016-05-15 07:45:17
【问题描述】:

考虑代码:

#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)};
}

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

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

我只是好奇是否有一种方法可以调用 converter 结构的强制转换运算符显式指定模板参数。语法:

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

没有用...

【问题讨论】:

    标签: c++ templates c++11 operator-overloading


    【解决方案1】:

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

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

    或者像这样

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

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

    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;
        }
    };
    

    并像这样使用它:

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

    【讨论】:

    • 所以没有办法传递第二个模板参数,这可能很有趣......?
    • 作为一种变通方法,您可以将模板化函数 cast 添加到您的 struct converter。然后,当可以隐式转换时,operator T 将被调用,当您需要显式转换时,您可以调用您的模板化函数。
    猜你喜欢
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多