template overloading and SFINAE working only with functions but not classes

混江龙づ霸主 提交于 2019-12-18 02:16:46

问题


can someone explain why the compiler accepts only this code

template<typename L, size_t offset, typename enable_if< (offset<sizeof(L)), int >::type =0>
void a_function(){}

template<typename L, size_t offset, typename enable_if< (offset==sizeof(L)), int >::type =0>
void a_function(){}

but not this:

template<typename L, size_t offset, typename enable_if< (offset<sizeof(L)), int >::type =0>
class a_class{};

template<typename L, size_t offset, typename enable_if< (offset==sizeof(L)), int >::type =0>
class a_class{};

The compiler sees the second class template as a redefinition of the first.


回答1:


You have to use specialization for classes. Typically, it is done with an extra parameter:

template <class P, class dummy = void>
class T;

template <class P>
class T<P, typename enable_if<something, void>::type> {
   the real thing
};

Two class (or class template) declarations with the same name should always declare the same class or class template (or be a specialization, in which case it is still the same template).




回答2:


You probably want to do something like this (ideone.com link):

#include <iostream>

template< typename PL, size_t pOffset, int pC = int( sizeof(PL) ) - int( pOffset ) >= 0 ? ( int( sizeof(PL) ) - int( pOffset ) == 0 ? 0 : 1 ) : -1 >
class TClass
{
};

template< typename PL, size_t pOffset >
class TClass< PL, pOffset, -1 >
{
 public:
  static int const sI = -1;
};

template< typename PL, size_t pOffset >
class TClass< PL, pOffset, 0 >
{
 public:
  static int const sI = 0;
};

template< typename PL, size_t pOffset >
class TClass< PL, pOffset, 1 >
{
 public:
  static int const sI = 1;
};

int main(void )
{
 TClass< char, 0 > lC0;
 TClass< char, 1 > lC1;
 TClass< char, 2 > lC2;

 std::cout << lC0.sI << " : " << lC1.sI << " : " << lC2.sI << std::endl;

 return ( 0 );
}

Program output:

1 : 0 : -1


来源:https://stackoverflow.com/questions/9079746/template-overloading-and-sfinae-working-only-with-functions-but-not-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!