c++ - c++中的模板类型成员变量

标签 c++ templates

我正在尝试根据我的模板中编写的内容更改成员变量的类型。

例如A<64, 64>应该让我的成员成为 int_128 可悲的是,我不知道如何使用模板类型,而且我找到的每个教程都只对模板函数有帮助。

我的类(class)看起来像

template<int x, int y>
class A{

    private:
    TYPETOBEGENERIC m_variable
}

有没有办法在构造函数中做到这一点

if( x+y <= 64){ TYPETOBEGENERIC = int_64 }
    else{TYPETOBEGENERIC = int_128}

我不想在模板中添加特定类型<>。结构 A<64, 64> 应该保持不变。

最佳答案

constexpr bool lessThan64(int a,int b) {
    return (a+b) < 64;
} 
template<int x, int y>
class A{
    using type = typename std::conditional<lessThan64(x,y),int_64,int_128>::type;
    private:
    type m_variable;
}

使用 constexpr 函数获得编译时元编程,我们可以在编译时评估这些值,然后使用 std::conditional 在两种类型之间进行选择。

编辑: 对于两种以上的类型,您可以使用可变参数模板或显式特化。

template<unsigned int I,typename... Sizes>
struct select;

template<unsigned int I,typename T,typename... Sizes>
struct select<I,T,Sizes...>:select<N-1,Cases...>
{
}    

template<unsigned int I,typename T,typename... Sizes>
struct select<O,T,Sizes...>
{
    using type =T
}

You would obviously need a constexpr function to differentiate between the types.

关于c++ - c++中的模板类型成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325907/

相关文章:

c++ - 将 Armadillo 函数传递给用户定义的函数

c++ - 在 C++ 中声明对象的问题

c++ - 对象组合 - 无法访问对象属性

c++ - 使用模板函数从 CSV 文件中读取数字

c++ - 无法使用没有参数的模板化方法实例化模板化类

c++ - 模板、静态和 dll

c++ - 我想在C++中实现map,因为我无法检查 vector 大小并为我制作的 vector 提供值

c++ - 分配给 `char* x = new char[32]` 的内存过多

c++ - openmp读取数据时会出现虚假共享吗?

c++ - GLFW - 在不使用循环的情况下保持窗口