c++ - 是否可以指定模板类的两个部分? ( '<' 之前和 '< >' 内部的部分)

标签 c++ templates

class trytemplate
{
public:
    //////// 1
    template <typename T>
    trytemplate(const T& p)
    {
        std::cout << p << std::endl;
    }

    //////// 2
    template <typename U>
    trytemplate(const std::vector<U>& p)
    {
        std::cout << p[0] << " " << p.size() << std::endl;
    }

    //////// 3
    template <typename U, typename V>
    trytemplate(const V<U>& p)
    {
        std::cout << p[0] << " " << p.size() << std::endl;
    }
};

ctor 2 工作正常,但我想让它像 3(3 不编译)。
这样我就可以做类似的事情:

int i = 123;
trytemplate o1(i); // call ctor 1

std::vector<float> v1(1, 123.0f);
trytemplate o2(v1); // ideally can be deduced by compiler, and call ctor 3

MyVector<float> v2(1, 123.0f);
trytemplate o3(v2); // ideally can be deduced by compiler, and call ctor 3

在这种情况下,我可以传入任何类似 vector 的容器,只需确保该类具有 operator[]size()

所以问题是:是否可以让 ctor 像数字 3 一样?
或者有什么更好的方法吗?

附言如果有人可以建议更好的标题,那么我会更改它,谢谢!

最佳答案

使用模板模板参数

template <template<typename> class V, typename U>
trytemplate(const V<U>& p)
{
    std::cout << p[0] << " " << p.size() << std::endl;
}

您还可以添加可变参数模板以接受采用多个模板参数的类模板。

template <template<typename...> class V, typename... Params>
trytemplate(const V<Params...>& p)
{
    std::cout << p[0] << " " << p.size() << std::endl;
}

请注意,如果您使用非可变(第一个)版本,那么您传入的类模板应该只接受一个模板参数。这意味着它不能与 std::vector 一起使用因为它需要第二个模板参数,即分配器类型(默认参数为 std::allocator<T> )。如果你的编译器不支持可变参数模板,比如没有 Nov CTP 的 VS2012,那么使用这个

template <template<typename, typename> class V, typename U, typename A>
trytemplate(const V<U, A>& p)
{
    std::cout << p[0] << " " << p.size() << std::endl;
}

关于c++ - 是否可以指定模板类的两个部分? ( '<' 之前和 '< >' 内部的部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24299894/

相关文章:

Jquery 模板插件

c++ - 使用模板减少类(class)规模的合理方法?

c++ - 模板分配类型区分

c++ - 继承在类外定义的运算符

c++ - 基本类型与内置类型 C++ 之间有什么区别

使用模板的 C++ 方法定义

c++ - 初始化作为模板实例的基类不需要模板参数吗?

c++ - .cpp 文件中模板类的非模板方法 - undefined reference ?

c++ - 在C++中将数字转换为具有指定长度的字符串

C++:array1 = array2 vs使用循环将array2的值分配给array1