gpt4 book ai didi

c++ - 将 enable_if 与模板特化结合使用

转载 作者:行者123 更新时间:2023-11-30 03:45:53 24 4
gpt4 key购买 nike

我想创建函数 get_type_name。对于属于某些集合示例的类型是数字、几何等,我想制作一个 get_type_name 函数,它使用 enable_if 和类型特征。对于不属于特定集合的每种类型,我想专门化它自己的 get_type_name 函数。这是我的代码,我收到以下编译器错误并且无法弄清楚原因:

error C2668: 'get_type_name': ambiguous call to overloaded function could be 'std::string get_type_name(myenable_if::type *)' or '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>();

}

最佳答案

这是一个工作版本。

#include <iostream>
#include <string>
#include <vector>
#include <iostream>
template<bool B, typename T = void>
struct myenable_if {};
template<typename T>
struct myenable_if<true, T> { typedef T 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_helper(void* t, char)
{
return "normal";
}
template<class T>
typename myenable_if<is_number<T>::value, std::string>::type get_type_name_helper(void* t, int)
{
return "number";
}

//get_type_name for specific type
template<>
std::string get_type_name_helper<std::string>(void* t, char)
{
return std::string("string");
}

template <class T>
std::string get_type_name(void* t = 0)
{
return get_type_name_helper<T>(t, 0);
}
int main() {
std::string n = get_type_name<int>();
std::cout << n << '\n';
n = get_type_name<std::string>();
std::cout << n << '\n';
n = get_type_name<float>();
std::cout << n << '\n';
return 0;
}

参见 Live Demo

关于c++ - 将 enable_if 与模板特化结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34461281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com