C ++:为什么递归模板化别名被禁止?

时间:2017-10-05 22:10:20

标签: c++ templates recursion alias template-meta-programming

为什么无法编译:

template<typename T, int N>
using vec = vector<vec<T, N - 1>>;
template<typename T>
using vec<0> = T;

虽然将它嵌套到一个结构中工作得很好:

template<typename T, int N>
struct foo {
    using vec = vector<typename foo<T, N - 1>::vec>;
};
template<typename T>
struct foo<T, 0> {
    using vec = T;
};

如果你可以用更详细的构造替换它,那么在别名中禁止递归的理由是什么?

请参阅:https://godbolt.org/g/YtyhvL

1 个答案:

答案 0 :(得分:2)

  

如果你可以用更详细的构造替换它,那么在别名中禁止递归的理由是什么?

你在那里回答了你自己的问题。你有机制做你想要的。而且,由于定义的别名只是一种简写,为什么复杂的语法会复杂化?

您使用该结构来实现机器,并使用别名来提供好的类型名称:

String your_string = ""; // Variable to copy the new string into
String userString = "this_string"; // String to do replacement on
int lastCharacter = userString.length() - 1; // Length of inputted string
String replace = "g"; // Thing to replace
String replaceWith = "d"; // Thing to replace with
int count = 0; // Index of character in string
while(lastCharacter >= 0) {
    char nextCharacter = userString.charAt(count);
    String nextCharacterString = nextCharacter + "";
    if (nextCharacterString.equals(replace)) {
        nextCharacterString = replaceWith; // I changed += to = because we want to replace, not add
    }
    System.out.print(nextCharacterString);
    your_string = your_string + nextCharacterString; // This is where we add the correct character to the string
    lastCharacter--;
    count++;
}

短而甜蜜,语言语法更简单。