Suppose I'm writing a template function foo that has type parameter T. It gets an object of type T that must have method bar(). And inside foo I want to create a vector of objects of type returned by bar.
In GNU C++ I can write something like that:
template<typename T>
void foo(T x) {
std::vector<__typeof(x.bar())> v;
v.push_back(x.bar());
v.push_back(x.bar());
v.push_back(x.bar());
std::cout << v.size() << std::endl;
}
How to do the same thing in Microsoft Visual C++? Is there some way to write this code that works in both GNU C++ and Visual C++?
You can do that in standard c++
template<typename T>
struct id { typedef T type; };
template<typename T>
id<T> make_id(T) { return id<T>(); }
struct any_type {
template<typename T>
operator id<T>() const { return id<T>(); }
};
template<typename T, typename U>
void doit(id<T>, U& x) {
std::vector<T> v;
v.push_back(x.bar());
v.push_back(x.bar());
v.push_back(x.bar());
std::cout << v.size() << std::endl;
}
template<typename T>
void foo(T x) {
doit(true ? any_type() : make_id(x.bar()), x);
}
See Conditional Love for an explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With