在Switch passed type from template中提到了标签分派。
是否有可能(以及如果可以)做一些类似的事情:
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>();上面的代码导致编译器抱怨对重载函数的模糊调用,但我希望最后两行传达使用的意图。
Thx
发布于 2012-08-20 22:17:21
您可以使用std::enable_if和std::is_same (C++11),或者它们的boost等效项:
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()
{ ... }发布于 2012-08-20 22:37:25
具有不同数量模板参数的函数模板相互重载,因此您不是在定义专门化,而是重载。像这样的东西应该是有效的:
struct Tag1 {};
struct Tag2 {};
template<class T> struct MapResult;
template<> struct MapResult<Tag1> { typedef double Result; };
template<> struct MapResult<Tag2> { typedef char const* Result; };
template<class T>
typename MapResult<T>::Result get();
template<> double get<Tag1>() {return 1.2;}
template<> char const *get<Tag2>() {return "hello";}发布于 2012-08-20 23:23:26
无法推断get的第二个模板参数,因为它只作为返回类型出现:谁能说get<Tag1>()是对get<Tag1, double>的特定调用,而不是get<Tag1, int>?例如,如果您要调用get<Tag1, double>(),则调用将解析为正确的专业化认证。
但是,我怀疑您并不是真的希望get成为具有两个模板参数的函数模板:返回类型可能是第一个参数的函数。因此,我建议您这样声明get:
namespace result_of {
template<typename T>
struct get;
}
template<typename T>
typename result_of::get<T>::type get();其中result_of::get将是计算预期结果类型的元函数。为了简单起见,我们将把所有的鸡蛋放在result_of::get篮子里,而不是专门化函数模板get:
namespace result_of {
template<typename T>
struct get;
}
template<typename T>
typename result_of::get<T>::type get()
{ return result_of::get<T>::apply(); }
namespace result_of {
template<>
struct get<Tag1> {
typedef double type;
static type apply()
{ return 1.3; }
};
template<>
struct get<Tag2> {
typedef const char* type;
static type apply()
{ return "hello"; }
};
}一般而言,专门化类模板比专门化函数模板要常见得多,而在需要专门化函数模板的情况下,通过让函数模板将其实现完全委托给类模板,通常可以使其变得更简单。
https://stackoverflow.com/questions/12039239
复制相似问题