功能模板专业化与模板类 [英] Function template specialization with a template class

查看:150
本文介绍了功能模板专业化与模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

功能模板的部分专业化

任何地方解决我的问题,因为如果我搜索的关键字,我想出将给我解决方案适合不同的问题。我知道这之前必须提出,只是找不到解决方案。

I can't find anywhere a solution for my problem, because if I search with the keywords I come up with would give me solutions suited for different problems. I understand that this must been asked before, just can't find a solution.

假设我有一个函数模板:

Suppose I have a function template:

template<class any> print(any value);

我可以这样专门化,让我们说一个 int

I can specialize it like this for let's say a int:

template<> print<int>(int value)
{
    std::cout << value;
}

但现在的问题,我想要使用向量。因为向量类是一个模板类,所以变得很难。

But now the problem, I want it to work with a vector as well. Since the vector class is a template class it becomes difficult.

专门为这样的函数:

template<class any> print<vector<any> >(vector<any> value) {}

将生成以下错误(MinGW g ++):

Will generate the following error (MinGW g++):

FILE: error: function template partial specialization 'print<vector<any> >' is not allowed

请注意,函数print只是一个例子。 strong>

Note that the function print is just an example.

如何解决这个问题?

推荐答案

一个一般的解决方法,其中函数模板只是将作业委托给类模板成员函数:

There is a general workaround in which the function-template just delegates the job to class template member functions:

#include <vector>
#include <iostream>

template <typename T> struct helper {
    static void print(T value) { std::cout << value; }
};
template <typename T> struct helper<std::vector<T>> {
    static void print(std::vector<T> const &value) { }
};

template <typename T>
void print (T const &value) {
    // Just delegate.
    helper<T>::print (value);
}


int main () {
    print (5);
    std::vector<int> v;
    print (v);
}

然而,如果你可以通过简单的函数重载(如ecatmur和Vaughn Cato),这样做。

However, if you can come by with simple function overloading (as suggested by ecatmur and Vaughn Cato), do so.

这篇关于功能模板专业化与模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆