是否可以使用标签分派来确定返回类型 [英] Is it possible to use tag dispatching to determine return type
本文介绍了是否可以使用标签分派来确定返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
标签调度在从模板切换传递的类型中提及。
是否可能(以及如何实现)执行以下操作:
Is it possible (and how if it is) to do something like:
struct Tag1 {};
struct Tag2 {};
template<class T, typename R>
R get();
template<>
double get<Tag1>() {return 1.3;}
template<>
char const *get<Tag2>() {return "hello";}
double aDouble = get<Tag1>();
char const *aString = get<Tag2>();
上述代码导致编译器抱怨对重载函数的模糊调用,但我希望最后两个。
The above code causes the complier to complain about ambiguous call to overloaded function, but I hope the last two lines communicate the intention of usage.
Thx
推荐答案
使用 std :: enable_if
和 std :: is_same
(C ++ 11) p>
You could use std::enable_if
and std::is_same
(C++11), or their boost equivalents:
template <typename Tag>
typename std::enable_if<std::is_same<Tag, Tag1>::value, double>::type get()
{ ... }
template <typename Tag>
typename std::enable_if<std::is_same<Tag, Tag2>::value, char const *>::type get()
{ ... }
这篇关于是否可以使用标签分派来确定返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文