What are the differences between C ++ and Java / C # Generics patterns and what are the limits?

I read an interesting article / topic / discussion from here , and I had the following questions:

  • What are the limitations of Java / C # generics?
  • What is possible with C ++ templates that are not possible using Java / C # generics?

Edit 1 Other recommended questions Eric Lippert

  • What are some patterns that are possible with C # generators but impossible with C ++ templates?
  • What is the difference between typical C # true types and Java type erase types?
+5
source share
4 answers

First of all, you can read my 2009 article on this topic .

++ # , ++ . ++ :

  • PRO: " T "; Ts, , , , .

  • CON: " T ".

# , , : , , vs .

  • PRO: . , .

  • CON: . , , .

# , , , , , .

  • PRO: .

  • CON: .

, . # IL , , . , , . , List<object> List<string>, jitted- . List<int> List<short> .

  • PRO: , .

  • CON: .

# . , , .

:

  • PRO: .

  • CON: .

  • CON: , .

, , ++ - :

class D<T> 
{
    class S { }
    D<D<T>.S> ds;
}

# . .

++, , D<int>? D<D<int>.S>, . D<D<D<int>.S>.S>... .

+9

Java/#?

Java , , ++.

- ++, Java.

- (templated) () .

?

, / , , ( ) / #/Java/ .

, , , , , , Java/#, .

++?

, , . () , Java .


++ Generics, Java/#?

++ , #/Java , .

+3

Java Generics , . Sun , , . :

// This applies to JDK 1.5, so I won't use <>.
List<Number> list = new ArrayList<Number>();
list.add(2.0);
list.add(-2);
list.add(new BigDecimal("1.23456789");

List list = new ArrayList();
Double temp = new Double(2.0); // boxing
if (!temp instanceof Number) throw new ClassCastException();
list.add(temp);
// Similar for -2 and the BigDecimal.

, instanceof .

, list.getClass() == ArrayList.class , ++. List<Boolean> . , ++, :

template<int length, int time, int mass>
class measurement {...}

, .

+3

MSDN # generics ++ :

  • # generics ​​ , ++. , #, .
  • # , C {}.
  • # ; .
  • # : .
  • # .
  • # .
  • # , . ++ .

, .

++, #, Java-: true ( ).

#include <iostream>
template<unsigned U>
struct Fac{ enum { value = U * Fac<U-1>::value};};
template<>
struct Fac<0>{ enum { value = 1};};
template<unsigned U>
struct Fib{ enum {value = (Fib<U-1>::value + Fib<U-2>::value)};};
template<>
struct Fib<0>{ enum {value = 0};};
template<>
struct Fib<1>{ enum {value = 1};};
template<unsigned U>
void show(){
    show<U-1>();
    std::cout << "Fib(" << U << ")=" << Fib<U>::value << "\t" << "Fac(" << U << ")=" << Fac<U>::value << std::endl;
}
template<>
void show<0>(){}

int main(int argc, char** argv){
    show<12>();
}

http://ideone.com/Gdf3W

Edit

++ , # Java have. Boost - (Boost Concept Check Library). ++ 11 <type_traits>, - .

+1

All Articles