gpt4 book ai didi

c++ - 为什么const对不是boost_is_pair?

转载 作者:行者123 更新时间:2023-12-02 09:57:45 25 4
gpt4 key购买 nike

正如我在boost is_pair implementation上看到的那样,一个const对(或volatile对)不是一对。
有这个原因吗?

最佳答案

这是因为它的实现方式。为了使其适用于const std::pair,您必须提供相应的特化:

// DO NOT DO THIS IN REAL CODE - EXAMPLE ONLY
template<class T1 , class T2>
struct is_pair<const std::pair<T1 , T2>> : public std::true_type {};
而且,您必须为rvalue,lvalue等提供相同的重载。因此,通常的解决方案是提供没有任何限定符的类型。为此有一个 std::decay。或者从C++ 20开始,您可以使用 std::remove_cvref

std::decay applies lvalue-to-rvalue, array-to-pointer, andfunction-to-pointer implicit conversions to the type T, removescv-qualifiers, and defines the resulting type as the member typedeftype.


当然,C++模板中的任何问题都可以通过引入另一个模板来解决。您可以提供自己的模板化结构 is_pair_d。这是基于std的解决方案,但也可以与 boost一起使用。
#include <utility>
#include <type_traits>

template< class T >
struct is_pair : std::false_type {};

template< class T1 , class T2 >
struct is_pair< std::pair< T1 , T2 > > : std::true_type {};

template< class T >
struct is_pair_d : is_pair<typename std::decay<T>::type> {};

// a helper function for value
template<class T>
inline constexpr bool is_pair_d_v = is_pair_d<T>::value;

int main()
{
std::pair<int,int> p1;
const std::pair<int,int> p2;
auto &&p2_r = p2;
auto &p2_l = p2;

static_assert(is_pair<decltype(p1)>::value);
static_assert(!is_pair<decltype(p2)>::value);
static_assert(is_pair<std::decay_t<decltype(p2)>>::value); // C++11
static_assert(is_pair<std::remove_cvref_t<decltype(p2_r)>>::value); // C++20

static_assert(is_pair_d_v<decltype(p1)>);
static_assert(is_pair_d_v<decltype(p2)>);
static_assert(is_pair_d_v<decltype(p2_r)>);
static_assert(is_pair_d_v<decltype(p2_l)>);

return 0;
}
@Scheff提供了一个 coliru link。还有 godbolt link。您可以在那里使用代码。

关于c++ - 为什么const对不是boost_is_pair?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64385382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com