根据参数类型实例化重载的类模板

问题描述 投票:0回答:1

我有一个

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
在这里不起作用?我可以解决这个问题吗?

c++ templates c++11
1个回答
0
投票

可以使用部分特化,具体取决于类型

std::is_reference
T
类型特征的值。如果类型
T
为参考,则选择第一类;否则优先选择第二类。

示例:

template<typename T, bool = std::is_reference<T>::value>
struct Container
{
    ...
};

template<typename T>
struct Container<T, true>
{
    ...
};
© www.soinside.com 2019 - 2024. All rights reserved.