【发布时间】:2019-05-26 20:33:37
【问题描述】:
查看std::is_same的实现我们可以看到一些内部函数(继承自integral_constant)。为了方便,我复制一下g++代码:
template<typename _Tp, _Tp __v>
struct integral_constant {
static constexpr _Tp value = __v;
typedef _Tp value_type;
typedef integral_constant<_Tp, __v> type;
constexpr operator value_type() const noexcept { return value; }
constexpr value_type operator()() const noexcept { return value; }
};
template<typename, typename>
struct is_same : public integral_constant<bool, false> { };
template<typename _Tp>
struct is_same<_Tp, _Tp> : public integral_constant<bool, true> { };
这为我们提供了几个如何使用它的选项:
bool a1 = is_same<int, int>{}; // instantiate & then cast implicitly
bool a2 = is_same<int, int>(); // instantiate & then cast implicitly
bool a3 = is_same<int, int>::value; // use static member
bool a4 = is_same<int, int>{}(); // instantiate & then use operator()
bool a5 = is_same<int, int>{}.operator()(); // instantiate & then use operator()
我想知道这些额外功能有哪些用例,以及为什么会使用例如像
这样的简短实现 template<class, class> constexpr bool is_same = false;
template<class T> constexpr bool is_same<T,T> = true;
还不够?那么我们可以只写bool a = is_same<int,int>而不写{}或()或::value。
任何想法表示赞赏。
【问题讨论】:
-
is_same比变量模板早了大约十年。在 C++11 中,这是最直接、最方便的实现。如果它现在被发明出来,它的设计可能会有所不同。 -
你描述的是
std::is_same_v
标签: c++ templates c++17 constexpr