【发布时间】:2016-03-05 15:59:36
【问题描述】:
这是一个代码 sn-p,我将使用它来检查可变参数模板类型是否唯一:
template <typename...>
struct is_one_of;
template <typename F>
struct is_one_of<F> {
static constexpr bool value = false;
};
template <typename F, typename S, typename... T>
struct is_one_of<F, S, T...> {
static constexpr bool value =
std::is_same<F, S>::value || is_one_of<F, T...>::value;
};
template <typename...>
struct is_unique;
template <>
struct is_unique<> {
static constexpr bool value = true;
};
template <typename F, typename... T>
struct is_unique<F, T...> {
static constexpr bool value =
is_unique<T...>::value && !is_one_of<F, T...>::value;
};
int main() {
constexpr bool b = is_unique<bool, int, double>::value;
constexpr bool c = is_unique<int, char, int>::value;
static_assert(b == true && c == false, "!");
}
有没有什么方法可以使用 C++14 和 C++1z 中引入的功能使这段代码更短和/或更简洁?或者有没有更好的方法来使用新功能达到同样的效果?
对于 C++1z,我的意思是:最新版本的 Clang 和 GCC 中已经提供的功能。
【问题讨论】:
-
不,这很简洁。但是,当引入折叠表达式时,您将能够执行以下操作:
constexpr static bool value = std::is_same<F, T>::value || ... -
@BrianRodriguez:我认为这需要圆括号。
-
你可以用一点小技巧让
is_one_of更简洁一点:coliru.stacked-crooked.com/a/3b9755f28193a13b -
@PiotrSkotnicki 是的,完全正确。它是否使用了除折叠表达式之外的任何新功能(C++11 中不存在或未开发到该阶段)?
标签: c++ c++14 variadic-templates template-meta-programming c++17