我有一个
Container<T>
类,其中包含 T
类型的元素。 T
可能是也可能不是引用类型,我想以不同的方式对待它们(即,Container<int>
和Container<const int &>
有不同的实现)。我尝试过类似的事情
template<typename T, typename = typename std::enable_if<std::is_reference<T>::value>::type>
struct Container {
...
};
template<typename T, typename = typename std::enable_if<!std::is_reference<T>::value>::type>
struct Container {
...
};
但是编译器抱怨重新定义了
Container
。为什么 enable_if
在这里不起作用?我可以解决这个问题吗?
可以使用部分特化,具体取决于类型
std::is_reference
的 T
类型特征的值。如果类型 T
为参考,则选择第一类;否则优先选择第二类。
示例:
template<typename T, bool = std::is_reference<T>::value>
struct Container
{
...
};
template<typename T>
struct Container<T, true>
{
...
};