- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我想为某些类型的类专门化类,例如基于 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
// Expected
string is_int: 0, is_str: 1
// Expected
int is_int: 0, is_str: 0
// Not expected
非常感谢您的帮助,在此先感谢您
最佳答案
您需要保留第二个参数(由 ::type
别名的类型)未指定或 void
以便它与主模板的默认参数匹配:
struct TestT<T,
std::enable_if<std::is_arithmetic<T>::value>::type>
您还需要在 std::enable_if
语句之前使用 typename
,或者使用 std::enable_if_t
(并省略 : :类型
):
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
和类型特征来测试字符串:
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>();
};
关于c++ - 为什么编译器不接受基于 enable_if 的特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30655659/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 4 年前。
正如您在 this travis.yml 中看到的那样文件,我的代码依赖于一些第三方库,我在构建项目之前将它们安装在远程系统上。 Travis 每次推送提交时都会下载并构建这些库,这可以避免吗?我的意
我是一名优秀的程序员,十分优秀!