【发布时间】:2019-12-03 10:29:12
【问题描述】:
在我的 Qt 项目中,我经常需要访问当前日期/时间。由于不同的数据类型(尤其是字符串类型)需要此值,因此我编写了以下模板:
/* used constants */
const bool UTC_TIME = true;
const bool LOCAL_TIME = !UTC_TIME;
const char* vsoft::iot_opcua::Constants::DateTimeFormat = "yyyy-MM-dd hh:mm:ss.zzz";
template< class T = QDateTime >
auto curDateTime( const bool acbAsUTC = LOCAL_TIME ) -> std::conditional_t< ( std::is_same< T, QString >::value ) ||
( std::is_same< T, std::string >::value ) ||
( std::is_same< T, char* >::value ) ||
( std::is_same< T, const char* >::value )
, T /* explicit string cast */
, QDateTime /* default return type */
>
{
QDateTime lDateTime( QDateTime::currentDateTime() );
if ( acbAsUTC )
{
lDateTime = lDateTime.toUTC();
}
if constexpr ( std::is_same< T, QString >::value )
{
return lDateTime.toString( vsoft::iot_opcua::Constants::DateTimeFormat );
}
if constexpr ( std::is_same< T, std::string >::value )
{
return lDateTime.toString( vsoft::iot_opcua::Constants::DateTimeFormat ).toStdString();
}
if constexpr ( ( std::is_same< T, char* >::value ) || ( std::is_same< T, const char* >::value ) )
{
return lDateTime.toString( vsoft::iot_opcua::Constants::DateTimeFormat ).toStdString().c_str();
}
return lDateTime;
}
但编译器在最后一行显示编译器错误 C2440:“return: cannot convert from 'QDateTime' to 'QString'”
return lDateTime;
为什么编译器要强制转换?所有显式允许的返回类型之前都已处理,因此唯一剩下的返回类型应该是 QDateTime。
【问题讨论】:
-
你尝试返回不同的类型。例如,lDateTime.toString 和 lDateTime
-
这不能回答你的问题,但你为什么不直接使用模板特化 (en.cppreference.com/w/cpp/language/template_specialization)。我认为那会更干净。