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)
唯一的问题是,这太冗长了,以至于使某些事情变得难以辨认.
是否有任何最好和最简洁的方式来达到相同的结果而没有任何性能打击或解雇任何诠释学讨论?
提前致谢!
你完全可以避免result_of这样:
static_cast< decltype(point{}.x()) >( cast_me )
Run Code Online (Sandbox Code Playgroud)
请注意,如果point不能保证DefaultConstructible,您应该使用std::declval如下:
static_cast< decltype(std::declval<point>().x()) >( cast_me )
Run Code Online (Sandbox Code Playgroud)
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)