我正在尝试根据我的模板中编写的内容更改成员变量的类型。
例如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/