首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于推导型定义浮点常数

基于推导型定义浮点常数
EN

Stack Overflow用户
提问于 2022-05-12 13:55:20
回答 1查看 36关注 0票数 0

我有一个函数模板,它接受三维向量(任何有括号操作符和三个元素:MyCustom3DVectorfloat[3]double*等的东西)。并从中计算出一些东西。签名是这样的:

代码语言:javascript
复制
template <typename Vec3> 
constexpr auto compute_stuff(const Vec3& v);

在这个函数中,我需要定义常量1/5。问题是底层类型可以是浮动的,也可以是双的。我需要提取我的Vec3的底层类型。我可以用

代码语言:javascript
复制
using T = std::remove_reference_t<decltype(std::declval<Vec3>()[0])>;
constexpr auto oneFifth = T{1.0/5.0};

但这看起来是丑陋的,不必要的复杂。有更好的方法继续吗?

EN

回答 1

Stack Overflow用户

发布于 2022-05-12 14:26:53

我会为此写一种类型特征。

假设您希望支持指向数组的第一个元素的指针,那么具有value_type的容器和数量有限的没有value_type成员别名的容器:

代码语言:javascript
复制
#include <type_traits>
#include <iostream>
#include <vector>

template <typename T,typename = void> struct value_type;
// either its a pointer
template <typename T> struct value_type<T*,void> { using type = T; };
// or it has value_type
template <typename T> struct value_type<T,std::void_t<typename T::value_type>> { using type = typename T::value_type;};

// for convenience
template <typename T> using value_type_t = typename value_type<T>::type;

// ..or it doesn't have a value_type member alias
// some custom container
struct my_vector {
    // no value_type 
    double* data;
};    
// specialization for custom container
template <> struct value_type<my_vector> { using type = double;};


int main()
{
    std::cout << std::is_same_v< int,value_type_t<std::vector<int>>>;
    std::cout << std::is_same_v<double,value_type_t<double*>>;
    std::cout << std::is_same_v<double,value_type_t<my_vector>>;

    // oneFifth
    value_type_t<my_vector> oneFifth{1.0/5.0};
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72216920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档