繁体   English   中英

如何定义类内的模板化变量

[英]How to define a templated variable which is inside a class

我有两个文件quantity.hmain.cpp ,其内容如下

文件quantity.h

#include <iostream>
#include <utility>
template <typename T = unsigned int>
class quantity
{
    enum volume {ltr,gallon,oz};

    public:
    using ret = std::pair<volume,T>;
    ret get_volume()
    {
        return std::make_pair(ltr,5);
    }
    
}; 

然后我有main.cpp

#include<quantity.h>
int main() {
    quantity <unsigned int> q1;
    ret t = q1.get_volume();

    return 0;
}

如果我只调用q1.get_volume();它就会编译但我想将结果存储在std::pair ret中,它在quantity.h文件中声明/定义。 我得到代码的编译错误为

error: 'ret' was not declared in this scope

使用 auto,让编译器为你做推演工作:

#include <iostream>
#include <utility>

template <typename T = unsigned int>
class quantity
{
    enum volume { ltr, gallon, oz };

public:

    auto get_volume()
    {
        return std::make_pair(ltr, 5);
    }

};

int main() 
{
    quantity <unsigned int> q1;
    auto t = q1.get_volume();
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM