2013-10-15 97 views
1

的目的是否有可能键入别名的类的对象,例如类型别名的自定义类

using Potion = Collectable("Potion"); 

然后,如果我们有一个方法例如

void print_collectable(const Collectable& item) 
{ 
    // print stuff from collectable i.e. 
    std::cout << item.get_name() << std::endl; 
} 

我们可以通过药水代替可收集(“药水”)

print_collectable(Potion) vs print_collectable(Collectable("Potion")) 

这将有望然后打印“药水”

显然,我们可以创建一个名为药水即Collectable potion(//...)的对象,但我想知道,如果我们可以用上面创建临时对象,将是有益的,当我们不需要以其他方式存储对象和/或节省一些打字

+0

但我们**确实需要**的对象。 'print_collectable'需要一个。 – Angew

回答

5

使用常数。

const Collectable Potion("Potion"); 
2

也许这是你在找什么:

struct { 
    operator Collectable() const { return Collectable("Potion"); } 
} Potion; 
每次调用

print_collectable(Potion); 

它会创建一个临时的对象与Collectable("Potion")并传递到print_collectable

其中

相关问题