Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrained member functions and explicit template instantiation

G++ and Clang++ agree that the following snippet is not valid C++:

template<int dim, int rank>
struct Tensor {};

template<int dim>
double InnerProduct(Tensor<dim, 1> const &, Tensor<dim, 1> const &)
  { return 0.0; }

template<int dim>
double DoubleInnerProduct(Tensor<dim, 2> const &, Tensor<dim, 2> const &)
  { return 0.0; }

template<int dim, int rank>
class Field
{
private:
  static double Dot(Tensor<dim, rank> const &u, Tensor<dim, rank> const &v) requires (rank == 1)
    { return InnerProduct(u, v); }

  static double Dot(Tensor<dim, rank> const &u, Tensor<dim, rank> const &v) requires (rank == 2)
    { return DoubleInnerProduct(u, v); }
};

template class Field<2, 1>;
template class Field<2, 2>;

The error message states that even the functions with unsatisfied constraints are instantiated:

error: no matching function for call to ‘DoubleInnerProduct(const Tensor<2, 1>&, const Tensor<2, 1>&)’
   22 |     { return DoubleInnerProduct(u, v); }

I can make it work in a number of ways (for example, declaring Dot as templates with a default parameter equal to rank to which the constraints are applied), but I expected it to work.

In general, shall I assume that template classes with member functions with constraints depending on their template parameters cannot be explicitly instantiated?

like image 340
metalfox Avatar asked Jun 30 '20 14:06

metalfox


People also ask

How do I instantiate a template function?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>(float original); Template arguments may be omitted when the compiler can infer them.

What is a templated function?

Function templates. Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.

Can member functions be declared as template?

Member functions can be function templates in several contexts. All functions of class templates are generic but are not referred to as member templates or member function templates. If these member functions take their own template arguments, they are considered to be member function templates.

How do you declare a template function in C++?

Defining a Function Template A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.


2 Answers

Explicit class template instantiation definitions are also explicit instantiation definitions of those members that have been defined at the point of instantiation

Consider the following simplified example:

template<int rank>
struct A {};

template<int rank>
struct Field {
    void dot(A<rank>) requires (rank == 1) { (void)(1); }
    void dot(A<rank>) requires (rank == 2) { (void)(2); }
};

[temp.explicit]/11 states [emphasis mine]:

An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members (not including members inherited from base classes and members that are templates) that has not been previously explicitly specialized in the translation unit containing the explicit instantiation, provided that the associated constraints, if any, of that member are satisfied by the template arguments of the explicit instantiation ([temp.constr.decl], [temp.constr.constr]), except as described below. [...]

Which implies that an explicit instantiation definition that names only a class template specialization of Field, say

template struct Field<1>;

will also lead to the explicit instantiation definition of the dot overload which fulfills the constraint expression requires (rank == 1), but not for the overload with a constraint expression requires (rank == 2). However, the except as described below part leads us to [temp.explicit]/12, which states [emphasis mine]:

An explicit instantiation definition that names a class template specialization explicitly instantiates the class template specialization and is an explicit instantiation definition of only those members that have been defined at the point of instantiation.

Meaning that, for the simplified example above (followed by the explicit instantiation definition for Field<1>, as above), the passage above indicates the explicit instantiation definition of both dot overloads, as both have been defined at the point of the explicit instantiation definition of Field<1>. This, however, means an ODR-violation as there will be two definitions of Field<1>::void dot(A<1>).

// Not OK.
template<int rank>
struct A { };

template<int rank>
struct Field {
    void dot(A<rank>) requires (rank == 1) { (void)(1); }
    void dot(A<rank>) requires (rank == 2) { (void)(2); }
};

template struct Field<1>;

int main() {}

yielding the following error on Clang:

error: definition with same mangled name '_ZN5FieldILi1EE3dotE1AILi1EE' as  another definition
       void dot(A<rank>) requires (rank == 2) { }

Note that we may provide an explicit instantiation definition for, particularly, the dot non-template member of the Field class template for a given specialization of the latter, and GCC and Clang will happily accept it, indicating that the constraint expressions are respected when explicitly instantiating the overloaded, constrained functions:

// OK.
template<int rank>
struct A { };

template<int rank>
struct Field {
    void dot(A<rank>) requires (rank == 1) { (void)(1); }
    void dot(A<rank>) requires (rank == 2) { (void)(2); }
};

template void Field<1>::dot(A<1>);

int main() {}

but not when they are, as described above, implicitly given explicit instantiated definitions as per the [temp.explicit]/12 quote above, as this seems to provide separate instantiation definitions for both members (without respecting the constraint expression) and thus violating ODR.

The different behaviour from the compilers between the explicit instantiation definition of the class template specialization vs a non-template member function of the specialization is somewhat peculiar, but possibly the difference is that for the latter case, [temp.constr.constr]/2 applies [emphasis mine]

[...] Overload resolution requires the satisfaction of constraints on functions and function templates.


If we only declare but don't define the second overload, it will not be instantiated as part of the explicit instantiation definition (i.e., [temp.explicit]/12 does not apply for it) of Field<1>, and we will no longer have an ODR-violation:

// OK.
template<int rank>
struct A { };

template<int rank>
struct Field {
    void dot(A<rank>) requires (rank == 1) { (void)(1); }
    void dot(A<rank>) requires (rank == 2);
};

template struct Field<1>;

int main() {}

Now, why is this not failing for an implicit instantiation?

As per [temp.inst]/3 [emphasis mine]:

The implicit instantiation of a class template specialization causes

(3.1) the implicit instantiation of the declarations, but not of the definitions, of the non-deleted class member functions, member classes, scoped member enumerations, static data members, member templates, and friends; and [...]

such that the following example is accepted by both Clang and GCC:

template<int rank>
struct A { };

template<int rank>
struct Field {
    void dot(A<rank>) requires (rank == 1) { (void)(1); }
    void dot(A<rank>) requires (rank == 2) { (void)(2); }
};

int main() { 
    Field<1> f{};
    (void)f;
}

where, as per [temp.inst]/4, the dot overloads will not be instantiated as the Field<1> specialization is not referenced in a context that requires their definitions to exist.

Finally, however, we may note that the implicit instantiation of the dot static member function of the Field class template will respect the constraint expression, and instantiate the overload which fulfills the constraint on the rank non template parameter of the particular class template specialization:

#include <iostream>

template<int rank>
struct A { };

template<int rank>
struct Field {
    void dot(A<rank>) requires (rank == 1) { std::cout << "1"; }
    void dot(A<rank>) requires (rank == 2) { std::cout << "2"; } 
};

int main() { 
    Field<1>{}.dot(A<1>{}); // "1"
}

This is likely governed by [temp.constr.constr]/2, as quoted above.

like image 191
dfrib Avatar answered Sep 21 '22 01:09

dfrib


This is a bug of the c++20 experimental implementation of both GCC and Clang.

This is reported as GCC bug #77595.

In the c++20 paragraph [temp.explicit]/11:

An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members (not including members inherited from base classes and members that are templates) that has not been previously explicitly specialized in the translation unit containing the explicit instantiation, provided that the associated constraints, if any, of that member are satisfied by the template arguments of the explicit instantiation ([temp.constr.decl], [temp.constr.constr]), except as described below. [...]

According to this c++20 adendum "provided that the associated constraints, if any, of that member are satisfied" means that only one of the two Dot overload shall be explicitly instantiated.

The bolded clause "except as described below" was there in the c++17 standard. It does apply to the first clause "An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members". The interpretation of this exception has not changed with c++20. Probably that the commitee overlooked that, grammaticaly, it could be correct to apply the exception to the c++20 adendum.

Below is the c++17 version of this paragraph:

An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members (not including members inherited from base classes and members that are templates) that has not been previously explicitly specialized in the translation unit containing the explicit instantiation, except as described below.

In this shorter sentence the meaning is clear.

like image 36
Oliv Avatar answered Sep 22 '22 01:09

Oliv