Jest to kontynuacja pytanie do an answer do Is it possible to typedef a pointer-to-extern-“C”-function type within a template?Dlaczego szablony nie mogą znajdować się w zewnętrznych blokach "C"?
Ten kod nie skompilować z g++
, Visual C/C++ i Comeau C/C++ z zasadniczo ten sam komunikat o błędzie:
#include <cstdlib>
extern "C" {
static int do_stuff(int) {
return 3;
}
template <typename return_t_, typename arg1_t_>
struct test {
static void foo(return_t_ (*)(arg1_t_)) { }
};
}
int main()
{
test<int, int>::foo(&do_stuff);
return EXIT_SUCCESS;
}
g ++ mówi "błąd: szablon z C linkage", Visual C/C++ emituje błąd kompilatora C2894, a Comeau C/C++ mówi "błąd: ta deklaracja może nie mieć zewnętrznego powiązania" C ".
Chodzi o to, wszyscy są zadowoleni z:
#include <cstdlib>
extern "C" {
static int do_stuff(int) {
return 3;
}
struct test {
static void foo(int (*)(int)) { }
};
}
int main()
{
test::foo(&do_stuff);
return EXIT_SUCCESS;
}
Sekcja 7.5, specyfikacje hydraulika, od C++ standard stwierdza:
A C language linkage is ignored for the names of class members and the member function type of class member functions.
I nawet daje przykład:
extern "C" {
class X {
void mf(); // the name of the function mf and the member
// function's type have C++ language linkage
void mf2(void(*)()); // the name of the function mf2 has C++ language
// linkage; the parameter has type pointer to C function
};
}
Jeśli szablony były dozwolone w zewnętrznych blokach "C", wówczas funkcje członkowskie instancji miałyby C++ l tusz.
Dlaczego więc nie rozdział 14, szablonów z C++ 98, stan normalny:
A template name may have linkage (3.5). A template, a template explicit specialization (14.7.3), and a class template partial specialization shall not have C linkage.
Co to znaczy, że szablon "może" mieć powiązania? Czym jest powiązanie z szablonem?
Dlaczego zabronione jest posiadanie szablonu z łączem C, gdy klasa jest w porządku, a wszystkie funkcje składowe instancji szablonu (domyślny konstruktor, destruktor i przeciążenie operatora przypisania) miałyby powiązanie C++?
Ach, znalazł się na klauzulę, która uniemożliwia szablony mieć powiązania C! –