2017-05-30 57 views
0

C++中是否有任何方法可以在程序中存储数据类型(如int,char,std :: string等),然后使用该变量代替常规数据类型(例如:声明其他变量)?可用作数据类型的变量。

对于如: -

T = some-function("int") 
now std::vector <T> is equivalent to std::vector <int> ? 
+0

要在运行时做到这一点需要[*反射*](https://en.wikipedia.org/wiki/Reflection_(computer_programming))C++没有。一旦源文件被编译到[*翻译单元*](https://en.wikipedia.org/wiki/Translation_unit_(编程))中,大部分类型信息就消失了。为了在编译时使用* templates *,任何[良好的初学者书](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)都应该有帮助。 –

+1

使用模板。如果你想要一个在编译时不知道的泛型类型,可以使用'std :: variant' – paddy

回答

4

您可以使用模板和decltype
一个最小的,根据您的片断工作示例:

#include<vector> 

template<typename T> 
T some_function() { return {}; } 

int main() { 
    // t has type int 
    auto t = some_function<int>(); 
    // vec has type std::vector<int> now 
    std::vector<decltype(t)> vec; 
} 
0

可以别名类型(给他们另一个名字)与using关键字:

using vi = std:: vector<int>; // I recommend against such short names 
// ... 
vi some_vector_with_integers; 

当然,出现这种情况完全在编译时。

模板结束语此类声明允许编译程序:

template<int N> 
using X = std::conditional<(N > 42), int, double>:: type; 
0

C++是一种静态类型语言,这意味着类型几乎没有在运行时存在。函数返回类型完全由参数类型(const char*)定义,并且不能取决于参数值("int")。

计算流量可能受到类型的影响,通过超载 - 但反之亦然。因此,您不能通过调用某个函数来“计算”某个类型。

相反,您可以在编译时使用模板/ decltype/auto来生成复杂的和上下文相关的类型,或者使用多态类型。

多态类型确实具有运行时定义的行为:您可以使some-function返回抽象工厂,然后使用该工厂生成对象 - 在编译时它们的具体类型将是未知的。当然,你仍然需要用一些静态类型实例化vector - 通常是指向通用类的指针(AbstractType*)。

您提到int,charstd::string这一事实表明您可能不希望整个多态层次结构可以使用静态类型进行管理。

Here是一些模板,用于确定调用函数的结果类型。注意该函数甚至没有被调用 - 同样,返回类型只依赖于参数类型,而不是一些计算。