我有一个函数模板,它接受三维向量(任何有括号操作符和三个元素:MyCustom3DVector、float[3]、double*等的东西)。并从中计算出一些东西。签名是这样的:
template <typename Vec3>
constexpr auto compute_stuff(const Vec3& v);在这个函数中,我需要定义常量1/5。问题是底层类型可以是浮动的,也可以是双的。我需要提取我的Vec3的底层类型。我可以用
using T = std::remove_reference_t<decltype(std::declval<Vec3>()[0])>;
constexpr auto oneFifth = T{1.0/5.0};但这看起来是丑陋的,不必要的复杂。有更好的方法继续吗?
发布于 2022-05-12 14:26:53
我会为此写一种类型特征。
假设您希望支持指向数组的第一个元素的指针,那么具有value_type的容器和数量有限的没有value_type成员别名的容器:
#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};
}https://stackoverflow.com/questions/72216920
复制相似问题