C++ 14转换为返回类型的成员函数 - 简洁版

j4x*_*j4x 1 c++ casting type-conversion c++14

请将此视为我要做的最简单的工作示例,以揭示我的疑问:

#include <iostream>
#include <stdint.h>
#include <typeinfo>

using DefaultType = uint32_t;

class point
{
public:
    DefaultType x( ) const  { return DefaultType( 0 ); }
    DefaultType y( ) const  { return DefaultType( 0 ); }
};

int main( )
{
    long    cast_me = 0xaaaaaaaa;

    auto    casted = static_cast< std::result_of< decltype( &point::x )( point ) >::type >( cast_me );

    std::cout << "cast_me (" << typeid( cast_me ).name( )
        << ") has been casted (" << typeid( casted ).name( ) << ")" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

关键是,在给定的时刻,我需要将一个独立变量(cast_me在示例中)转换为与给定成员函数的返回类型匹配的另一个类型(point::x()在示例中).

这一行:

static_cast< std::result_of< decltype( &point::x )( point ) >::type >( cast_me )
Run Code Online (Sandbox Code Playgroud)

效果很好,我的示例程序给了我:

cast_me (l) has been casted (j)
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,这太冗长了,以至于使某些事情变得难以辨认.

是否有任何最好和最简洁的方式来达到相同的结果而没有任何性能打击或解雇任何诠释学讨论?

提前致谢!

Vit*_*meo 7

你完全可以避免result_of这样:

static_cast< decltype(point{}.x()) >( cast_me )
Run Code Online (Sandbox Code Playgroud)

直播wandbox示例


请注意,如果point不能保证DefaultConstructible,您应该使用std::declval如下:

static_cast< decltype(std::declval<point>().x()) >( cast_me )
Run Code Online (Sandbox Code Playgroud)

wandbox上的实例

  • @fljx没有听到过.你实际上并没有构建一个点,只是检查表达式的类型.实际上,`std :: declval <>()`甚至没有定义. (4认同)
  • @NathanOliver我认为不必,你可以做`declval <point&>`我相信. (3认同)

Nir*_*man 6

Vittorio的解决方案当然是正确的,而且更加简洁,但坦率地说,这就是typedef的用途:

class point
{
public:
    using ReturnType = DefaultType;
    ReturnType x( ) const  { return ReturnType( 0 ); }
    ReturnType y( ) const  { return ReturnType( 0 ); }
};

auto    casted = static_cast<point::ReturnType>( cast_me );
Run Code Online (Sandbox Code Playgroud)

  • @fljx为了更好的可维护性,您可以考虑按如下方式声明类型别名:`using ReturnType = decltype(std :: declval <point&>().x());`您现在可以更改`x()的返回类型`根据需要,无需修改两个地方. (2认同)