本文介绍了在模板函数中声明依赖未知类型的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在写一个类型为T的模板函数foo。它获取一个类型为T的对象,该对象必须有方法bar()。而在foo内部,我想创建一个由bar返回的类型的对象的向量。

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.

在GNU C ++中,我可以这样写:

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;
}

如何在Microsoft Visual C ++中做同样的事情?是否有一些方法来编写这个代码在GNU C ++和Visual C ++中都有效?

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++?

推荐答案

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);
}

查看。

这篇关于在模板函数中声明依赖未知类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 14:52
查看更多