如何使用模板或typedef在float/double矢量类型之间进行选择?

yon*_*yon 0 cuda

定位不同浮点精度(float/double)的常用方法是使用typedef

typedef float Real;
//typedef double Real;
Run Code Online (Sandbox Code Playgroud)

或者使用模板

template<typename Real>
...
Run Code Online (Sandbox Code Playgroud)

这很方便,但是任何人都有想法如何使用CUDA类型float2/float3/...和make_float2/make_float3/...?当然,我可以为所有人制作#defines或typedef,但这看起来不是很优雅.

jet*_*t47 5

您可以实现将连接类型和通道号的辅助类:

template <typename T, int cn> struct MakeVec;
template <> struct MakeVec<float, 3>
{
    typedef float3 type;
};
template <> struct MakeVec<double, 3>
{
    typedef double3 type;
};
// and so on for all combination of T and cn
Run Code Online (Sandbox Code Playgroud)

用法:

template <typename T>
void func()
{
    typedef typename MakeVec<T, 4>::type vec4_type;
    vec4_type vec4; // for T=float it will be float4, for T=double it will be double4
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到实现