我可以使用模板参数作为变量吗?

问题描述

我想根据如下模板参数分配内存:

PHP artisan vendor:publish --force --tag=livewire:assets

编译器将抛出类似以下错误

enum typeFlag {
kFloat32 = 0,kFloat64 = 1,kFloat16 = 2,kUint8 = 3,kInt32 = 4,kInt8  = 5,kInt64 = 6,kBool = 7,kInt16 = 8
};

template<typename dtype,typename ctx>
inline TBlob<dtype,ctx>::TBlob(const size_t &size): shape_{size} {
    switch(dtype){
        case kFloat32:
            dptr_ = new float[size];
            break;
        case kFloat64:
            dptr_ = new double[size];
            break;
...

我能否在保持error: expected primary-expression before ‘)’ token switch(dtype){ ^ 相同含义的情况下实现目标?

解决方法

您当然可以。我猜你当前的定义是这样的

template<typename dType> ... everything else

您应该将其更改为非类型参数,它将按预期工作。要么

template<int dType> ... rest of definition

template<typeFlag dType> ... rest of definition

应该可以使用,具体取决于您的语言版本。

您可以here进一步了解它。

,

似乎您要将非模板(枚举数)参数映射到类型:

#include <cstddef>

// Platform-independent type descriptions.
enum class TypeFlag {
kFloat32 = 0,kFloat64 = 1
    // ...
};

// Platform-specific TypeFlag to type mapping.
template<TypeFlag FLAG>
struct MappedType;

// Specialize type mapping for the platform-independent
// type representations (TypeFlag) that can be represented
// on this particular platform.
template<>
struct MappedType<TypeFlag::kFloat32> { using type = float; };

template<>
struct MappedType<TypeFlag::kFloat64> { using type = double; };

// ...

template<TypeFlag FLAG>
using MappedType_t = typename MappedType<FLAG>::type;

template<TypeFlag FLAG,std::size_t SIZE>
struct TBlob {
    using BlobType = MappedType_t<FLAG>;

    TBlob() {
        dptr_ = new BlobType[SIZE];
    }

    // ...

private:
    BlobType* dptr_;
};

请注意,double不一定在所有目标体系结构上都是64位浮点数,因此这种方法不一定可移植,并且可以说是针对特定平台的类型映射。