【发布时间】:2019-10-17 09:16:56
【问题描述】:
我有一个模板类 G:
template<int I>
class G {}
碰巧我需要 2 个基于 int I 的实现
如果它是一个单一的值,我总是能够做到:
template<>
class G<int Specific_I>
{
/*Implementation for that I*/
}
如果我有单一条件,即如果为真则使用 implementation_1,如果为假则使用 implementation_2,我可以使用给定 here 的建议
但是,我的情况比较一般。
假设我在I 上为每个实现定义了条件:
template<int I>
constexpr bool Condition_1 = /*whatever*/;
template<int I>
constexpr bool Condition_2 = /*whatever_v2*/;
这样便于阅读和根据需要进行扩展
如果在程序中调用特定I 时,由于没有或多个条件适用于特定I 而出现错误,我可以接受
明显的选择是使用std::enable_if_t
template<int I,
enable_if_t<Condition_1<I>>
>
class G
{
/*Implementation based on Condition_1*/
}
template<int I,
enable_if_t<Condition_2<I>>
>
class G
{
/*Implementation based on Condition_2*/
}
但这会导致错误
template parameter ‘typename std::enable_if<Condition_1<I>, void>::type <anonymous>’|
redeclared here as ‘typename std::enable_if<Condition_2<I>, void>::type <anonymous>’|
我在哪里犯了错误,我该如何解决?
【问题讨论】:
-
我发誓,如果我得到一个链接到我已经解释为“没有解决我的问题”的问题的“重复”标签......
-
这个问题还不清楚。你想要
I==0和I==1的不同定义吗? -
你定义了两次错误告诉你的相同模板,但不清楚你想要实现什么
-
@foreknownas_463035818 正如我所说的,我在每个实现中都有
constexpr的I条件 -
“在每个实现中”是什么意思?你有
Condition_1和Condition_2并且你想根据其中一个是否为true来选择实现?