元编程:函数定义的失败定义了一个单独的函数 [英] Metaprograming: Failure of Function Definition Defines a Separate Function

查看:202
本文介绍了元编程:函数定义的失败定义了一个单独的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案中,我根据类型的 is_arithmetic property:

  template< typename T> enable_if_t< is_arithmetic< T> :: value,string> stringify(T t){
return to_string(t);
}
template< typename T> enable_if_t<!is_arithmetic< T> :: value,string> stringify(T t){
return static_cast }

dyp建议,而不是类型的 is_arithm 属性, code> to_string 是为类型定义的模板选择条件。这显然是可取的,但我不知道如何说:


如果 std :: to_string 未定义,然后使用 ostringstream 重载。


声明 to_string 标准很简单:

  template< typename T& decltype(to_string(T {}))stringify(T t){
return to_string(t);
}

这是相反的标准,我不知道如何构建。这显然不工作,但希望它传达我正在尝试构造:

  template< typename T& enable_if_t<!decltype(to_string(T {}):: value,string>(T t){
return static_cast< ostringstream&>(ostringstream()<< t).str $ b}


解决方案

上周的委员会会议:

  template< class T> 
using to_string_t = decltype(std :: to_string(std: :declval< T>()));

template< class T>
using has_to_string = std :: experimental :: is_detected< to_string_t,T>

然后在 has_to_string 上为您的内容标记分派和/ / p>

您可以参阅现在的工作草案的TS 如何 is_detected 和朋友可以实现。它类似于 can_apply in @ Yakk的回答。


In this answer I define a template based on the type's is_arithmetic property:

template<typename T> enable_if_t<is_arithmetic<T>::value, string> stringify(T t){
    return to_string(t);
}
template<typename T> enable_if_t<!is_arithmetic<T>::value, string> stringify(T t){
    return static_cast<ostringstream&>(ostringstream() << t).str();
}

dyp suggests that rather than the is_arithmetic property of the type, that whether to_string is defined for the type be the template selection criteria. This is clearly desirable, but I don't know a way to say:

If std::to_string is not defined then use the ostringstream overload.

Declaring the to_string criteria is simple:

template<typename T> decltype(to_string(T{})) stringify(T t){
    return to_string(t);
}

It's the opposite of that criteria that I can't figure out how to construct. This obviously doesn't work, but hopefully it conveys what I'm trying to construct:

template<typename T> enable_if_t<!decltype(to_string(T{})::value, string> (T t){
    return static_cast<ostringstream&>(ostringstream() << t).str();
}

解决方案

Freshly voted into the library fundamentals TS at last week's committee meeting:

template<class T>
using to_string_t = decltype(std::to_string(std::declval<T>()));

template<class T>
using has_to_string = std::experimental::is_detected<to_string_t, T>;

Then tag dispatch and/or SFINAE on has_to_string to your heart's content.

You can consult the current working draft of the TS on how is_detected and friends can be implemented. It's rather similar to can_apply in @Yakk's answer.

这篇关于元编程:函数定义的失败定义了一个单独的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆