How to I get my class to infer the inner type of a parameter without explicitly referring to it? Look at the minimal example below:
#include <vector>
template <class T>
class foo {
public:
foo(std::vector<T> &x) :
_x(x) {
T dummy = x.front(); // Trying to trick the compiler here
}
private:
std::vector<T> _x;
};
int main() {
std::vector<int> a;
foo<int> b(a); // This works
foo c(a); // This fails
return 0;
}
I see that foo expects it’s argument to be a vector<int>, but it let’s me create an object of type T==[int] so it seems like it knows what the inner type is! Neverminding the fact that the assignment of dummy fails when a is empty … how can I refer to the nested inner type?
For obvious reasons.
foois a class template, you cannot instantiate an object of it without naming a template parameter.This is not like a function template, where the template arguments can be inferred through the function arguments.
fooin this case names a type (or should), not the constructor.In C++11, you might do this: