【问题标题】:C++ Proposal Function Returning A Type [closed]返回类型的 C++ 建议函数 [关闭]
【发布时间】:2015-07-14 21:35:18
【问题描述】:

由于有很多建议,我想问一下 C++ 中是否存在这样的事情,或者是否有任何建议做这样的事情。

想法:

template <typename T>
constexpr typename evalToType(int x, int y) {
    if(x > y)
        return T;
    else
        return int;
}

template <typename T, int x, int y>
evalToType<T>(x, y) SomeFunction() {
    return 0;
}

这样做的动机是微不足道和简单的,基本上是模板可能非常复杂并且变得非常不可读,所以为什么不将模板 SFINAE 的内容表达为基本上返回类型而不是值的 constexpr。

【问题讨论】:

  • 如果有有这样的提议,我希望它被拒绝。
  • @Captain Obvlious 请问为什么这是个坏主意?

标签: c++ templates c++11 c++14 constexpr


【解决方案1】:

这已经是可能的,但语法不同。因此,引入另一种语法并没有真正的好处。

template <typename T, int x, int y>
using some_name = std::conditional_t< (x>y), T, int >;

template <typename T, int x, int y>
some_name<T, x, y> SomeFunction() {
    return 0;
}

如您所见,该语言已经很有表现力了。

【讨论】:

  • 哦,我也刚刚意识到这确实不是一个好主意,因为复杂的计算可以用 constexpr 函数表示。我的坏:)。
【解决方案2】:

一些样板:

template<class T> struct tag{using type=T;};
template<class Tag> using type_t=typename Tag::type;

template<int x> using int_t = std::integral_constant<int, x>;
template<int x> constexpr int_t<x> int_v = {};

根据参数的类型,以函数 (C++14) 的形式返回标记类型的代码:

template<class T, int x, int y>
constexpr auto evalToType( int_t<x>, int_t<y> )
{
   return std::conditional_t< (x>y), tag<T>, tag<int> >{};
}

template<class T, int x, int y>
type_t<decltype(evalToType(int_v<x>, int_v<y>))>
SomeFunction() {
  return 0;
}

您可以将type_t&lt;decltype()&gt; 替换为:

#define TYPE_T(...) type_t<decltype(__VA_ARGS__)>

如果你愿意。

template<class T, int x, int y>
TYPE_T(evalToType(int_v<x>, int_v<y>))
SomeFunction() {
  return 0;
}

这很有趣。

【讨论】:

    猜你喜欢
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    相关资源
    最近更新 更多