2015-08-08 46 views
0

现在,我正尝试在C++中创建一个原型动态类型系统来回答Stack Overflow的另一个问题。有没有办法在C++中使用类型文字?

但是,我想知道如何能够从变体中选择特定类型。

我想要的基本上是将键直接转换为类型的函数,然后让程序根据该类型文字构造一个类型。

我想要什么(在伪代码):

std::string type; 

TYPE get_type(std::string) { ... } 

get_type(type) new_variable(); 
+0

这有帮助吗? http://en.cppreference.com/w/cpp/language/user_literal – Galik

+0

@Galik我不确定,但我倾向于说不,因为我认为在C++中没有'eval()'等价物,所以允许对于可变字符串常量运算符,如果在运行时无法动态评估C++代码,则意味着什么。 – VermillionAzure

+0

return(compile-time)* type *不能取决于std :: string的(运行时)值。 – Jarod42

回答

1

使用延续传递风格,sortof。

template<class T>struct tag{using type=T;}; 
template<class Tag>using type_t=typename Tag::type; 
#define TYPEOF(...) type_t<std::decay_t<decltype(__VA_ARGS__)>> 

template<class F> 
auto get_type(std::string s, F f) { 
    if (s=="int") 
    return f(tag<int>{}); 
    if (s=="double") 
    return f(tag<double>{}); 
} 

使用:

void do_stuff(std::string type) { 
    int x = get_type(type, [&](auto tag) { 
    TYPEOF(tag) var; 
    return 7; 
    }); 
} 
在这种情况下

var是类型type名称的变量。

请注意,所有分支都将被编译,所以所有分支必须生成有效的代码。

否则,不,这是不可能的,除非constexpr魔法。

相关问题