【发布时间】:2015-10-17 23:17:55
【问题描述】:
我正在尝试使用 SFINAE 做一个 excersize bu,但我得到一个我不理解的编译错误。
我有以下代码:
#include <cstddef> // for size_t & NULL
#include <memory>
#include <cstdlib>
#include <iostream>
#include <type_traits>
namespace more_container
{
template <typename T>
class raw_doubly_list
{
public:
template<typename T1, typename T2>
friend struct std::is_same;
public:
template <typename V>
struct elem_base
{
}; // struct elem_base
public:
#ifdef SMART_PTR
typedef std::shared_ptr<elem_base<T> > list_type;
#elif defined RAW_PTR
typedef elem_base<T>* list_type;
#endif
public:
typedef T value_type;
struct delete_elem
{
}; // struct delete_elem
private:
/*
类型名 std::enable_if::value,list_type >::type
ei_alloc_memory(void* p_void,const list_type& p_temp)
{
return temp(static_cast*>(new (p_void) elem_base(p_temp->m_object)),delete_elem());
}
*/
typename std::enable_if< std::is_same< list_type,elem_base<T>* >::value,list_type >::type
ei_alloc_memory(void* p_void,const list_type& p_temp)
{
return static_cast<elem_base<T>*>(new (p_void) elem_base<T>(p_temp->m_object));
}
list_type alloc_memory(const list_type& p_temp);
private:
list_type p_to_head;
}; // class raw_doubly_list
//alloca memory
template <typename T>
typename raw_doubly_list<T>::list_type raw_doubly_list<T>::alloc_memory(const list_type& p_temp)
{
list_type ret = NULL;
void* p_void = malloc(sizeof(elem_base<T>));
return ei_alloc_memory(p_void,p_temp);
}
}
int main()
{
return 0;
}
如果我理解得很好,如果第一个为真,则 enable_if 返回第二个模板参数。否则失败。 那么对于一个模板成员函数,签名由输入参数和返回值组成。
如果我使用注释函数,我会得到一个编译错误(不能重载)。为什么 ? 它的签名应该不同,因为返回类型应该不同。
提前致谢。
供测试使用:
g++ -Wall -std=c++0x -DRAW_PTR test6.cpp
完整的错误信息:
test6.cpp:63:13: 错误: 'typename std::enable_if::elem_base*, more_container::raw_doubly_list::elem_base*>::value, more_container::raw_doubly_list::elem_base*>::type more_container ::raw_doubly_list::ei_alloc_memory(void*, more_container::raw_doubly_list::elem_base* const&)' 不能被重载 ei_alloc_memory(void* p_void,const list_type& p_temp) ^ test6.cpp:57:13: 错误: with 'typename std::enable_if::elem_base*, std::shared_ptr::elem_base > >::value, more_container::raw_doubly_list::elem_base*>::type more_container:: raw_doubly_list::ei_alloc_memory(void*, more_container::raw_doubly_list::elem_base* const&)' ei_alloc_memory(void* p_void,const list_type& p_temp)
【问题讨论】:
标签: compiler-errors sfinae enable-if