gpt4 book ai didi

c++ - 我如何确定模板参数参数是否是模板内结构中另一个类的实例? C++

转载 作者:搜寻专家 更新时间:2023-10-31 00:10:43 24 4
gpt4 key购买 nike

我有一个 .h包含我所有模板的文件和一个 .cpp与我的主要文件。

.h的一部分模板:

   template<int N, int P>
struct BOUND {
static inline int eval(int v) {
//...
return 1;
};
};

template<class K>
struct VAL_x {
static inline int eval(int v) {
//...
return 1;
};
};

template<int L, class K>
struct LIT {
static inline int eval(int v) {
//...
return 1;
};
};

template<class A, class B, class K>
struct ADD {
static inline int comp_b(int v){
// HERE check if class A is LIT or VAL_x
//...
return 2;
};
};

这是我调用 main() 的方式这个模板:

int main() {

typedef ADD<VAL_x<BOUND<2,3> >, LIT<2, BOUND<2,3> >, BOUND<2,3> > FORM;
FORM exec_form;

int y = 2;

int bounds = exec_form.comp_b(y);

return 0;
}

我怎么知道ADD::comp()我的功能 struct ,如果传递的参数是特定类的实例(例如 LIT<> )?这些参数可以按任何顺序传递(例如所有参数可以是 LIT ,或者只有第二个)

注意:除了VAL_x 之外还有其他结构, LIT , BOUNDADD .

最佳答案

选项 #1

为每个感兴趣的类模板引入一个单独的特征(C++03 在这里帮助不大)。

template <bool B> struct bool_constant { static const bool value = B; };
template <bool B> const bool bool_constant<B>::value;

template <typename T> struct is_LIT : bool_constant<false> {};
template <int L, int M> struct is_LIT<LIT<L, M> > : bool_constant<true> {};

template <typename T> struct is_VAL_x : bool_constant<false> {};
template <int K> struct is_VAL_x<VAL_x<K> > : bool_constant<true> {};

template <class A, class B>
struct ADD
{
static inline int comp_b(int v)
{
if (is_LIT<A>::value && is_VAL_x<B>::value)
{

}

return 2;
}
};

DEMO

选项 #2

使用通用自定义特征,其特化检测传递的类型是否是指定模板模板参数的实例(如果特化匹配,即 T 是类模板的实例X):

template <template <int> class X, typename T>
struct is_template { static const bool value = false; };

template <template <int> class X, int N>
struct is_template<X, X<N> > { static const bool value = true; };

template <typename A, typename B>
struct ADD
{
static inline int comp_b(int v)
{
if (is_template<VAL_x, A>::value && is_template<LIT, B>::value)
{
}

return 2;
}
};

DEMO 2

选项 #3

使用标记分派(dispatch),可能为返回 true/false 的其他类模板添加重载,使其类似于选项 #1。此解决方案还依赖于重载解析,与那些约束较少/通用的函数模板相比,它更喜欢更专业的函数模板。

template <typename T> struct tag {};

template <typename A, typename B>
struct ADD
{
static inline int comp_b(int v)
{
return comp_b(v, tag<A>(), tag<B>());
}

template <int M, int N>
static inline int comp_b(int v, tag<LIT<M> >, tag<VAL_x<N> >)
{
return 1;
}

template <typename T, typename U>
static inline int comp_b(int v, tag<T>, tag<U>)
{
return 2;
}
};

DEMO 3

关于c++ - 我如何确定模板参数参数是否是模板内结构中另一个类的实例? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36989510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com