为什么编译器不拾取基于enable_if的专门化
Why specialization based on enable_if is not picked up by compiler
我想为某些类型的类专门化class,例如基于std::is_arithmetic。虽然编译器不会"看到"我的基于"enable_if"的专门化,并选择原则/主模板。你能帮我解决这个问题吗?下面是用g++ 4.8编译后的代码片段和输出
#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
//不期望
我真的很感激任何帮助,并提前感谢您
您需要将第二个参数(以::type
别名的类型)保留为未指定或void
,以便它与主模板的默认参数相匹配:
struct TestT<T,
std::enable_if<std::is_arithmetic<T>::value>::type>
您还需要在std::enable_if
语句之前使用typename
,或者使用std::enable_if_t
(省略::type
):
struct TestT<T, std::enable_if_t<std::is_arithmetic<T>::value>>
第二个专门化也是如此:
template<>
struct TestT<std::string>
{
static const bool is_int = false;
static const bool is_str = true;
};
最后,在这个专门化中,is_int
应该设置为true
:
template<typename T>
struct TestT<T, std::enable_if_t<std::is_arithmetic<T>::value>>
{
static const bool is_int = true;
static const bool is_str = false;
};
现场演示
一个更好的版本可能是保持单一的专门化,使用std::is_same
来测试int
,使用类型trait来测试字符串:
template<class T>struct is_string:std::false_type{};
template<>struct is_string<std::string>:std::true_type{};
template<std::size_t N>struct is_string<char const(&)[N]>:std::true_type{};
template<>struct is_string<char const*>:std::true_type{};
template<>struct is_string<char const*const>:std::true_type{};
template<>struct is_string<char const*volatile>:std::true_type{};
// on and on...
template<typename T>
struct TestT
{
static const bool is_int = std::is_same<T, int>();
static const bool is_str = is_string<T>();
};
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- SFINAE with boost enable if