Topic: Template friend function


Author: "Carl Daniel" <carl@pixami.com>
Date: Fri, 1 Jun 2001 16:31:06 GMT
Raw View
> We don't need a language extension for this. You can implement it in
> current C++:
>
>
> // Tip o' the hat to Andrei
> template <bool Test> struct static_assert;
> template <> struct static_assert<true> {};
>
> // Valid only if there are no bits in Src that aren't in Dst
> template <unsigned Src, unsigned Dst> struct convert_check:
>   static_assert<((Src | Dst) == Dst)> {};
>
> // Template for qualified types
> // Each bit in Mask represents a type qualifier
> template <typename T, unsigned Mask> class qualified {
>   public:
>     qualified(T t = T()):
>       value_(t) {}
>     operator T() const {
>       static_assert<(Mask == 0)>();
>       return value_;
>     };
>     template <typename T2, unsigned Mask2>
>       qualified(qualified<T2, Mask2> src):
>         value_(src.value_) {
>           convert_check<Mask2, Mask>();
>         }
>     template <unsigned Mask2> friend qualified<T, Mask2>
>       qualified_cast(qualified src) {
>         return qualified<T, Mask2>(src.value_);
>       }
>   private:
>     T value_;
> };
>
> // Define a couple of type qualifiers
> const unsigned magic(1);
> const unsigned tainted(2);
>
> int main() {
>   int i(42);                             // Plain int
>   qualified<int, magic> m;               // Magic int
>   qualified<int, (magic | tainted)> mt;  // Magic, tainted int
>   mt = i;                                // OK
>   // m = mt;                             // This won't compile
>   m = qualified_cast<magic>(mt);         // But this will
>   return 0;
> }
>
>
> (Tested on GCC 2.95.3)
>

.... but apparently not tested with Comeau C++:

Comeau C/C++ 4.2.45.2 (Apr 12 2001 10:06:52) for ONLINE_EVALUATION
Copyright 1988-2001 Comeau Computing.  All rights reserved.
MODE:strict errors C++

"4893.c", line 42: error: identifier "qualified_cast" is undefined
    m = qualified_cast<magic>(mt);         // But this will
        ^

1 error detected in the compilation of "4893.c".


So who's right?  Is the OP's code valid C++?  If it is, what exactly is the
signature of the global function template qualified_cast<?????>(?????)?

-cd




---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.research.att.com/~austern/csc/faq.html                ]