Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function type be a class template parameter?

The code below is rejected by VC++ 2012 with "error C2207: 'A::bar' : a member of a class template cannot acquire a function type".

int Hello(int n)
{
    return n;
}

template<class FunctionPtr>
struct A
{
    A(FunctionPtr foo)
        : bar(foo)
    {}

    FunctionPtr bar;
};

int main()
{
    A<decltype(Hello)> a(Hello);

    return 0;
}

Why?

like image 224
xmllmx Avatar asked Nov 05 '12 13:11

xmllmx


People also ask

Can function be a template argument?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Can a member function be a 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.

What are non-type parameters for templates?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type.

Can we use non-type parameters as argument templates?

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.


1 Answers

gcc is a bit more friendly regarding this error :

error: field 'A<int(int)>::bar' invalidly declared function type

The simplest solution is to declare bar as a function pointer :

FunctionPtr *bar;

In this case, decltype(Hello) evaluates to int(int) not int(*)(int).

like image 110
BЈовић Avatar answered Oct 14 '22 21:10

BЈовић