c++ - C++ 17 make函数返回类型模板,然后为支持的类型编写实现

标签 c++ templates c++17

我想转换以下示例代码

class Example{
public:
    float getFloat(){return 0;}
    int getInt(){return 0;};
    std::vector<float> getFloatVector(){
        return std::vector<float>();
    }
};

插入语法稍好的代码-例如它看起来应该像这样:
class Example2 {
    public:
        template <class T> virtual T get();
    };
    Example2::get<float>(){
        return 0;
    }
    Example2::get<int>(){
        return 0;
    }
    Example2::get<std::vector<float>>(){
        return std::vector<float>();
    }

当然,第二个示例代码不会编译,但是它显示了我想如何使用Example类:
Example2 example;
LOGD("%d",example.get<float>());

最佳答案

成员函数模板不能声明为virtual,因此您可以将主模板的声明更改为

class Example2 {
public:
    template <class T> T get();
};

然后像
template <>
float Example2::get<float>(){
    return 0;
}
template <>
int Example2::get<int>(){
    return 0;
}
template <>
std::vector<float> Example2::get<std::vector<float>>(){
    return std::vector<float>();
}

从C++ 17开始,我们可以像这样使用constexpr if
class Example2 {
public:
    template <class T> T get();
};

template <typename T>
T Example2::get() {
    if constexpr (std::is_same_v<T, float>) 
        return 0;
    else if constexpr (std::is_same_v<T, int>) 
        return 0;
    else if constexpr (std::is_same_v<T, std::vector<float>>) 
        return std::vector<float>();
    else
        return ...;
}

关于c++ - C++ 17 make函数返回类型模板,然后为支持的类型编写实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61224074/

相关文章:

c++ - 为什么模板实参用作另一个模板的模板参数时不能推导出来?

c++ - (boost::)outcome 的错误处理:在具有组合和继承的构造函数中使用

c++ - 在 C++ 中检测运算符是否存在和可调用(考虑 static_asserts)

c++ - 模板模板推导给我一个通用引用的错误

c++ - 试图修复转换警告

C++如何将 vector 与模板一起使用?

c++ - 大小由模板参数定义的成员数组,但为什么没有对零大小数组发出警告?

javascript - 将 Jquery 函数放在一个单独的文件中 - Joomla

c++ - 如何在有限的空间中选择最少N个元素?

c++ - char 的实现定义是否影响 std::string?