Boost Static Assertion for Type Comparision

2019-07-02 03:09发布

问题:

The following problem gives me compiler errors and I am not sure how to write it correctly

struct FalseType { enum { value = false }; };
struct TrueType { enum { value = true }; };


template <typename T1, typename T2>
struct IsSame
{
typedef typename FalseType Result;
};


template <typename T>
struct IsSame<T,T>
{
typedef typename TrueType Result;
};

BOOST_STATIC_ASSERT( (IsSame< Foo::FooClass1 , Foo::FooClass1 >::Result::value) );

This static assertion should not fail when used, but somehow the compiler NVCC from CUDA gives me the following error:

error C2338: (IsSame< Foo::FooClass1 , Foo::FooClass1 >::Result::value)

I dont know what to do, all other STATIC ASSERTIONS work but the type comparision does not , what is wrong up there? Typo? Brackets?

I cant get my type comparision to work under NVCC?

Any ideas?

IT SEEMS THAT MSVC (which is routed to by NVCC) has its problems as well with the above version.... hm...

============= EDIT ======================== HERE A SNIPPET WHICH DOES NOT WORK IN MSVC!

This snipped should compile in MSVC, but it does not, so I assume compiler bug:

error C2118: negative subscript ( WHHHHHYYYYYY) strange....

#include <iostream>


using namespace std;


struct FalseType { static const bool  value = false ; };
struct TrueType {  static const bool  value = true ; };


template <typename T1, typename T2>
struct IsSame
{
  typedef ::FalseType Result;
  static const bool result = false;
};


template <typename T>
struct IsSame<T,T>
{
typedef ::TrueType Result;
static const bool result = true;
};

namespace OtherType{
   struct Type1{};
};

template< typename _T> // Settings from below
struct Settings{
   typedef _T myT;
   typedef char static_assert_failed[ ((IsSame< _T,OtherType::Type1>::Result::value)) ? 1 : -1 ]; // USE HERE only ::result works, (BUT WHY)
};

int main(){

   cout << (IsSame<OtherType::Type1,OtherType::Type1>::Result::value)<< endl;

}

回答1:

typedef typename FalseType Result;
typedef typename  TrueType Result;

This is wrong, because FalseType and TrueType aren't dependent names and therefore typename is illegal here.

It should be

typedef FalseType Result;
typedef  TrueType Result;

Update

It seems that

IsSame < _T, OtherType::Type1 >::Result::value 

is illegal. The thing is that

IsSame < _T, OtherType::Type1 >::Result 

must be qualified by typename but syntactically it is impossible, that is, the following is illegal, too

(typename IsSame <_T, OtherType::Type1 >::Result)::value 

I found the following solution which makes it work.

typedef typename IsSame <_T, OtherType::Type1 >::Result RealResult;
typedef char static_assert_failed[RealResult::value ? 1 : -1];

HTH.