是否可以为初始化创建模板,如下所示:
template <typename C> typename C::value_type fooFunction(C& c) {...};
std::vector<string> vec_instance;
fooFunction(cont<0>(vec_instance));
fooFunction(cont<1>(vec_instance));一般来说,我感兴趣的是有没有可能使用整数指定模板(即。0)而不是真正的类型名称。如何实现上述目标呢?
发布于 2011-01-12 06:56:13
我不完全清楚你在问什么,但是下面的代码片段对我来说是有效的:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <typename C>
typename C::value_type fooFunction(const C & c) { return 0; };
/* note that fooFunction takes a ref-to-const, not a reference */
template<int N>
struct cont
{
public:
typedef int value_type;
cont(vector<string> vec) {};
};
int main()
{
std::vector<string> vec_instance;
fooFunction(cont<0>(vec_instance));
fooFunction(cont<1>(vec_instance));
}值得注意的两个变化:
template <typename T>,那么你所写的内容将不起作用。cont<>是如何定义的,但从你的用法来看,它一定是你构造为临时对象的。您在将此临时引用作为引用传递到fooFunction时会遇到问题。请注意,上面的示例将C作为引用传递给常量。发布于 2011-01-12 06:49:56
是的,您可以在非类型参数上参数化模板,如整数、指针和其他模板。例如:
template <typename T, int N> struct Array {
T data[N];
/* ... other functions ... */
};这些模板的工作原理与您所见过的所有其他模板一样,只是它们是通过整数值而不是类型来参数化的。
This link有更多关于这个主题的信息。“现代C++设计”和"C++模板:完整指南“也有很多关于如何做到这一点的信息。
发布于 2011-01-12 07:04:49
这就是你要找的吗?非类型模板参数:
template<int n> class Cont
{
public:
typedef int value_type;
};
template<>
class Cont<0>
{
public:
typedef double value_type;
value_type convert(const std::string& s) const
{
return atof(s.c_str());
}
};
template<>
class Cont<1>
{
public:
typedef long value_type;
value_type convert(const std::string& s) const
{
return atoi(s.c_str());
}
};
template <int n> typename Cont<n>::value_type fooFunction(const Cont<n>& cont, const std::string& s)
{
return cont.convert(s);
}
void test()
{
Cont<0> c0;
Cont<1> c1;
double d = fooFunction(c0,"1.0");
int i = fooFunction(c1, "-17");
}https://stackoverflow.com/questions/4663395
复制相似问题