gpt4 book ai didi

C++:如何专门针对左值和右值

转载 作者:太空狗 更新时间:2023-10-29 21:41:35 26 4
gpt4 key购买 nike

我想为具有特定标记 (is_gpio_class) 的类型创建一个装饰器,该标记针对右值(必须复制)和左值(存储引用)以不同方式实现。为了避免提及类型,我使用了一个返回修饰类型的函数模板。

#include <type_traits>
template< typename T > struct always_false : std::false_type {};

// type with the tag to indicate that it is suitable
struct gpio_class {
typedef void is_gpio_class;
};

// fallback match gives an error
template< class P, class dummy = void >
struct invert_x {
static_assert( always_false< P >::value, "no match" );
};

// this should match an lvalue
template< class P >
struct invert_x< P, typename P::is_gpio_class > : public gpio_class {
constexpr invert_x( P & pin ) {}
};

// 'factory' function that dispatches to the correct specialization
template< typename P >
invert_x< P > invert( P && pin ){ return invert_x< P >( pin ); }

int main(){
gpio_class pin4;

// this works
auto led0 = invert_x< gpio_class>( pin4 );

// but this does not match the specialization
auto led1 = invert( pin4 );
}

这在函数具有 & 参数时有效,但为了区分 rval 和 lval,我认为我必须将其作为 && 传递,然后以某种方式以不同方式匹配左值和右值,但如何匹配?

最佳答案

您只需在 invert 调用 invert_x 时从推导的 P 中移除引用性。使用 std::remove_reference_t :

template< typename P >
invert_x< P > invert( P && pin )
{
return invert_x< std::remove_reference_t<P> >( pin );
}

编辑:要支持右值和左值重载,请像这样使用标签分派(dispatch):

template< typename P >
invert_x< P > invert( P && pin )
{
return invert_x< std::remove_reference_t<P> >( pin,
std::is_lvalue_reference<P&&>());
}

并为 invert_x 的构造函数提供这些重载:

constexpr invert_x( P & pin, std::true_type/*This is the lvalue overload*/ ) {} 
constexpr invert_x( P & pin, std::false_type/*This is the rvalue overload*/ ) {}

关于C++:如何专门针对左值和右值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28514189/

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