小编Aya*_*973的帖子

C++模板:按类型返回值

我正在学习C++和模板来实现配置文件阅读器(http://www.adp-gmbh.ch/cpp/chameleon.html),我正在尝试为具有std::string内部存储的类创建模板,它可以在将其赋值给变量时返回其内部值(double,long double,float,string,uint16_t,uint32_t).

平台:Win10与Visual Studio社区2015 Update 1

class HybridType {
public:
    HybridType() {};
    explicit HybridType(const std::string& value) : internalStr(value) {}
    explicit HybridType(const char* value) : internalStr (std::string(value)) { }

    template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type>
    explicit HybridType(T numericValue) {
        std::stringstream strstr;
        strstr << std::setprecision(std::numeric_limits<T>::digits10 + 1) << numericValue;
        internalStr = strstr.str();
    }

    operator std::string() const { return internalStr; }

    template<typename T>
    operator T() const {
        if (std::is_same<T, std::uint16_t>::value) return std::stoi(internalStr);
        if (std::is_same<T, std::uint32_t>::value) return std::stoul(internalStr);
        if …
Run Code Online (Sandbox Code Playgroud)

c++ templates

2
推荐指数
2
解决办法
878
查看次数

标签 统计

c++ ×1

templates ×1