【发布时间】:2015-06-04 23:03:17
【问题描述】:
我想专门针对某些类型的类,例如基于 std::is_arithmetic 的类。尽管编译器没有“看到”我基于“enable_if”的专业化并选择了原理/主模板。你能帮我解决这个... 下面是用g++ 4.8编译后的sn-p代码和输出
#include < iostream >
#include < type_traits >
#include < string >
template < typename T1, typename T2 = void >
struct TestT
{
static const bool is_int = false;
static const bool is_str = false;
};
template < typename T>
struct TestT < T,
std::enable_if< std::is_arithmetic<t>::value, T >::type >
{
static const bool is_int = true;
static const bool is_str = false;
};
template < typename T>
struct TestT < std::string, T >
{
static const bool is_int = false;
static const bool is_str = true;
};
class enum TestE
{
Last
};
int main(int argc, char* argv[])
{
std::cout << "Enum is_int: " << TestT<TestE>::is_int
<< ", is_str: " << TestT<TestE>::is_str << std::endl;
std::cout << "string is_int: " << TestT<std::string>::is_int
<< ", is_str: " << TestT<std::string>::is_str << std::endl;
std::cout << "int is_int: " << TestT<int>::is_int
<< ", is_str: " << TestT<int>::is_str << std::endl;
return 0;
}
上面的输出是:
Enum is_int: 0, is_str: 0// 预期string is_int: 0, is_str: 1// 预期int is_int: 0, is_str: 0// 未预期
非常感谢您的帮助,并提前感谢您
【问题讨论】:
-
请发布一些可以编译的代码
标签: c++ c++11 template-specialization enable-if