【发布时间】:2026-02-17 03:25:01
【问题描述】:
这是我要实现的目标的简化示例。因此,它可能看起来有点傻,但请耐心等待。假设我有
template<int i>
class Class1{
foo(){cout<<"j is divisible by i, so we will hang out"<<endl;}
}
和一个class2 有一个固定的int j 变量:要么被这样一个int 模板化,要么有一个成员变量。我希望class2 实例只有在满足特定条件时才能调用foo(),在这种情况下,我想确保说(j%i==0)。
我能想到的最好的是:
template<int i>
class Class1{
static const int intParam=i;
template<bool true>
foo(){cout<<"j is divisible by i, so we will hang out"<<endl;}
}
然后类 2 会这样称呼它:
foo<class1::intParam%j>()
这不是很好。有没有更好的方法来做到这一点?我见过'std::enable_if'这有点相关,但我不太确定。
如果您想要更大的图景,这是一种信号/委托代理机制。在系统中,任务对象应该能够被执行者对象提供/请求,前提是它们与任务中指定的角色枚举(int i)匹配。本质上,这应该是基于枚举的设计,没有动态多态性。在 C++ 中有没有更好的方法来做到这一点?
【问题讨论】:
-
你试过
static_assert吗? -
@krzaq 查看我对建议答案的评论。
标签: c++ templates crtp enable-if static-polymorphism