c ++模板到模板参数

c ++模板到模板参数

问题描述:

最近我在测试一些c ++模板代码,我发现一个令人费解的错误。根据我对互联网的研究,特别是stackoverflow,这段代码是完全有效的,但是,编译器提出了编译时错误。错误位于代码下方。

recently i was testing some c++ template codes and i found one mind-boggling error. According to my research on internet in particular stackoverflow, this code is completely valid however, compiler raises compile time error. Error is located below of code.

代码

template<template<class> class C, typename T> void print(C<T>& c) {
}

int test() {
    vector<string> v(5, "Yow!");
    print(v);
    return 0;
}

编译器输出:
$ b

Compiler Output:

In function ‘int test()’:
error: no matching function for call to ‘print2(std::vector<std::basic_string<char> >&)’
note: candidate is:
note: template<template<class> class C, class T> void print2(C<T>&)

看起来有关定义或我的编译器有问题,我测试这个代码与g ++和clang ++,以确保没有任何编译器相关的问题。两者都引起了相同的错误。

It seems something is wrong about definition or my compiler but i tested this code with both g++ and clang++ in order to be sure about there is not any compiler dependent problem. Both of them raises same error.

我真的很感谢任何有意义的意见,旨在澄清这个问题。

I really appreciate any meaningful comments which aim to make clarification for this problem.

谢谢

std: :vector ,以 C 形式传递的类型具有多个模板参数。它有通常的元素类型,但也是一个分配器。解决这个问题最简单的方法是使用一个可变参数模板:

std::vector, the type being passed in as C, has more than one template parameter. It has the usual element type, but also an allocator. The easiest way to get around this while keeping a list of type arguments is to use a variadic template:

template<template<class...> class C, typename... Ts> void print(C<Ts...>& c)
                  ^^^^^^^^                   ^^^^^^             ^^^^^^^^

实际使用单个类型参数更容易,在大多数情况下,通过明确指定它们,如在Cheers的答案。如果你不关心类型参数,请随时跟踪它们。在容器的情况下,你甚至可以只从容器类型获得它们:

Actually using the individual type arguments is easier done, in most cases, by explicitly specifying them, as in Cheers' answer. If you don't care about the type arguments, feel free to not keep track of them. In the case of a container, you can even get them from just the container type:

template<typename Container> void print(Container& c) {
    typename Container::value_type t;
}