specific syntax question
templ开发者_如何学Goate <typename C> typename C::value_type fooFunction(C& c) {...};
std::vector<string> vec_instance;
fooFunction(cont<0>(vec_instance));
fooFunction(cont<1>(vec_instance));
In general i'm interested is it possible to specify template using integer (ie. 0) instead of true type name. And how to achieve above?
I'm not completely clear on what you're asking, but the following snippet works for me:
#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));
}
Two changes worth noting:
An integer is not a type, so if cont is declared
template <typename T>
, what you have written will not work.template <int N>
is the proper way to parameterize over an integral value, as templatetypedef mentioned.I'm not sure how
cont<>
is defined, but from your usage it must be an object you are constructing as a temporary. You will have trouble passing this temporary as a reference intofooFunction
. Note that my example above passes C as reference-to-const instead.
Yes, you can parameterize templates over non-type arguments like integers, pointers, and other templates. For example:
template <typename T, int N> struct Array {
T data[N];
/* ... other functions ... */
};
These templates work just like all the other templates you've seen, except that they're parameterized over integral values rather than types.
This link has some more info on the subject. "Modern C++ Design" and "C++ Templates: The Complete Guide" also have lots of info on how to do this.
Is this what you are after? Non-type template parameters:
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");
}
精彩评论