c ++ 11 enable_if错误 [英] c++11 enable_if error

查看:124
本文介绍了c ++ 11 enable_if错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了下面的C ++ 11的enable_if示例:

I saw the following example of enable_if for C++11:

struct is_64_bit
{
    static const bool value = sizeof(void*) == 8;
};

enable_if<is_64_bit::value, void>::type
my_memcpy(void* target, const void* source, size_t n)
{
    cout << "64 bit memcpy" << endl;
}

enable_if<!is_64_bit::value, void>::type
my_memcpy(void* target, const void* source, size_t n)
{
    cout << "32 bit memcpy" << endl;
}

据我所知,根据系统架构,my_memcpy可用于32或64位版本。但是我在编译时遇到以下错误:

As I understand, depending on the system architecture, the "my_memcpy" function will be available either for 32 or 64 bit versions. But I'm getting the following error at compilation :

error: ‘type’ in ‘struct std::enable_if<false, void>’ does not name a type

我有点困惑,因为我只想到32版本应该可用(我使用的是Linux Fedora 32位)。

I'm a bit confused because I thought only the 32 version should be available (I'm using Linux Fedora 32 bits).

这个例子可能有问题吗?或者我缺少某些东西?

Maybe is something wrong with this example? or Am I missing something?

谢谢。

推荐答案

模板 template< bool B,class T = void> struct enable_if 是专门的,因此当条件B true typedef类型 >。

The template template< bool B, class T = void > struct enable_if is specialized so that it only has a typedef type when the condition B is true.

您的编译器是正确的。在 struct std :: enable_if< false,void> 中没有类型的typedef。只有一个typedef在 struct std :: enable_if< true,void>

Your compiler is correct. There is no typedef for type in struct std::enable_if<false, void>. There is only a typedef in struct std::enable_if<true, void>.

a href =http://en.cppreference.com/w/cpp/types/enable_if =nofollow>此处。

For more info look here.

因此要解决你的问题,你需要确保 enable_if 其中有一个评价为 false 永远不会编译。您可以通过 SFINAE 的帮助实现此目标,方法是使 my_memcpy 一个函数模板。编译器将不会报告错误,当编译函数模板,其中B计算 false ,并将成功编译和使用函数,其中B计算 true

So to fix your problem you need to make sure that the enable_if which has a B that evaluates to false never gets compiled. You can achieve this with the help of SFINAE by making my_memcpy a function template. The compiler will then not report an error when failing to compile the function template where B evaluates to false and will successfully compile and use the function where B evaluates to true.

#include <iostream>
#include <type_traits>

using namespace std;


struct is_64_bit
{
   static const bool value = sizeof(void*) == 8;
};

template<typename T>
typename enable_if<is_64_bit::value, T>::type
my_memcpy(T* target, const T* source, size_t n)
{
  cout << "64 bit memcpy" << endl;
}

template<typename T>
typename enable_if<!is_64_bit::value, T>::type
my_memcpy(T* target, const T* source, size_t n)
{
  cout << "32 bit memcpy" << endl;
}

这篇关于c ++ 11 enable_if错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆