这是合法的C++代码吗

Is this legal C++ code?

本文关键字:C++ 代码      更新时间:2023-10-16

我感兴趣的是引用标准中具体段落的答案,而不仅仅是一般意见。

template <class T> struct wrapped
{
       wrapped(const T&) {}
};
template <class T> wrapped<T> wrappit(const T& x)
{
       return wrapped<T>(x);
}
template <class T> int run_function(const T& x, bool wrapped)
{
       if (wrapped) {
               return 0;
       } else {
               return run_function(wrappit(x), true) + 1;
       }
}
int main()
{
       const int result = run_function(0.5, false);
       return result;
}

符合要求的实现可能会拒绝此代码。见本标准附件B。

您的实现应该在其文档中包含某些限制,这些限制包括:

  • 递归嵌套模板实例化

从14.7.1(15):

实例化中有限递归的结果是未定义的。


关于你的代码:你不能用if做静态条件语句。相反,您需要某种功能性方法和部分专业化:

template <typename T, bool> struct run_function;
template <typename T> struct run_function<T, true>
{
    static int go(T const & x) { return 0; }
};
template <typename T> struct run_function<T, false>
{
    static int go(T const & x)
    { return 1 + run_function<T, true>::go(wrappit(x)); }
};

现在不再有无限递归了,因为这两个分支使用不同的模板,这些模板最终不会实例化更多的模板。