Template Errors

I heard that C ++ templates will not generate errors until they are used. It's true? Can someone explain to me how they work?

+3
source share
4 answers

Patterns follow a two-phase compilation model.

struct X{
private:
   void f(){}
};

template<class T> void f(T t){
   int;   // gives error in phase 1 (even if f(x) call is commented in main)
   t.f(); // gives error only when instantiated with T = X, as x.f() is private, in phase 2
}

int main(){
   X x;
   f(x);
}
+6
source

They generate compiler errors during compilation. They are compiled separately for each actual parameter passed as template argument (s) (this is different from Java Generics), for example, if I have:

template <typename T> class foo { ... }

and

int main() {
  foo<char> c;
  foo<int> i ;
}

the template is foocompiled twice, once for characters, once for ints.

( ) foo, .

"" ++ , , .

+1

,

, . , , . , , .

, .

0

,

template <Type value, class Y, ...>
...fn-or-class...

#define FN_OR_CLASS(VALUE, TYPE_Y, ...) \
...fn-or-class...

, /, , . #defines , , , , , .

, , . , , , , , . , - - , API- , , - ... . , ++ 0x Concepts: , - , , API .

template <class T>
struct X
{
    void f() { }
    void g() { T::whatever(); } // only error if g() called w/o T::whatever
};

int main()
{
    X<int> x;
    x.f();
    // x.g(); // would cause an error as int::whatever() doesn't exist...
}

SFINAE ( ), . , , " - fn (int)?".

0

Source: https://habr.com/ru/post/1760467/


All Articles