递归结束时的模板语法错误

时间:2015-03-10 16:27:08

标签: c++ templates c++11

有人可以告诉我下面的递归特化结束语法有什么问题吗?我以为我遵守了所有的规则。

#include <iostream>

template <typename StreamType = std::ostream, StreamType& stream = std::cout>
class StringList {
    template <typename...> class AddStrings;
  public:
    template <typename... Args> void addStrings (Args&&... args) {AddStrings<Args...>()(args...);}
};

template <typename StreamType, StreamType& stream>
template <typename First, typename... Rest>
class StringList<StreamType, stream>::AddStrings<First, Rest...> : AddStrings<Rest...> {
public:
    void operator()(First&& first, Rest&&... rest) {
        // do whatever
        AddStrings<Rest...>::operator()(std::forward<Rest>(rest)...);
    }
};

template <typename StreamType, StreamType& stream>
template <>
class StringList<StreamType, stream>::AddStrings<> {
    friend class StringStreamList;
    void operator()() const {}  // End of recursion.
};

int main() {
    StringList<> stringList;
//  stringList.addStrings ("dog", "cat", "bird");
}

我不理解错误消息:

Test.cpp:22:11: error: invalid explicit specialization before '>' token
 template <>
           ^
Test.cpp:22:11: error: enclosing class templates are not explicitly specialized
Test.cpp:23:39: error: template parameters not used in partial specialization:
 class StringList<StreamType, stream>::AddStrings<> {
                                       ^
Test.cpp:23:39: error:         'StreamType'
Test.cpp:23:39: error:         'stream'

2 个答案:

答案 0 :(得分:5)

这是重要的一点:

Test.cpp:22:11: error: enclosing class templates are not explicitly specialized

这意味着您无法定义作为非专业化模板成员的事物的显式特化。

class StringList<StreamType, stream>::AddStrings<> {

此处AddStrings明确专门化,但StringList不是。这是不允许的。

答案 1 :(得分:0)

尽管Jonhathan Wakely的建议有效,但对于那些非常喜欢将这样的类嵌套的人,因为它根本就没有在其他任何地方使用过,我想我们可以为AddStrings插入一个虚拟模板参数。现在我把它保持为一个内部阶级,正如我强烈要求的那样,以下现在编译:

#include <iostream>

template <typename StreamType = std::ostream, StreamType& stream = std::cout>
class StringList {
    template <typename, typename...> struct AddStrings;  // The first type is a dummy type.
  public:
    template <typename... Args> void addStrings (Args&&... args) {AddStrings<void, Args...>()(args...);}
};

template <typename StreamType, StreamType& stream>
template <typename T, typename First, typename... Rest>
class StringList<StreamType, stream>::AddStrings<T, First, Rest...> : AddStrings<T, Rest...> {
  public:
    void operator()(First&& first, Rest&&... rest) {
        // do whatever
        std::cout << first << ' ';
        AddStrings<T, Rest...>::operator()(std::forward<Rest>(rest)...);
    }
};

template <typename StreamType, StreamType& stream>
template <typename Dummy>
class StringList<StreamType, stream>::AddStrings<Dummy> {
  public:
    void operator()() const {}  // End of recursion.
};

int main() {
    StringList<> stringList;
    stringList.addStrings ("dog", "cat", "bird");
}