【发布时间】:2015-12-25 17:57:02
【问题描述】:
我想创建函数 get_type_name。对于属于某个集合示例的类型是数字、几何等,我想做一个 get_type_name 函数,它使用具有类型特征的 enable_if。对于不属于特定集合的每种类型,我想专门化其自己的 get_type_name 函数。这是我的代码,我得到以下编译器错误,不知道为什么:
错误 C2668:“get_type_name”:对重载函数的模糊调用 可能是 'std::string get_type_name(myenable_if::type *)' 或 'std::string get_type_name(void *)'
template<bool B, typename T = void>
struct myenable_if {};
template<typename T>
struct myenable_if<true, T> { typedef void type; };
template<class T>
struct is_number
{
static const bool value = false;
};
template<>
struct is_number<int>
{
static const bool value = true;
};
template<class T>
std::string get_type_name(void* v=0);
//get_type_name for specific type
template<>
std::string get_type_name<std::string>(void*)
{
return std::string("string");
}
//get_type_name for set of types
template<class T>
std::string get_type_name(typename myenable_if<is_number<T>::value>::type* t=0)
{
return std::string("number");
}
int main()
{
std::string n = get_type_name<int>();
}
【问题讨论】:
-
函数不能部分特化。你这里有一个重载并且编译器是正确的:第一个和第三个模板在这里同样好。
-
@Gernot1976 那么你知道为什么代码不能编译了。
-
@Gernot no, they cannot be
标签: c++ templates template-meta-programming