Constexpr, which returns the address of a template function instance

Consider the following example:

#include <utility>
#include <iostream>

struct bar
{
    void baz() { std::cout << "bar::baz" << std::endl; }
};

template <typename Signature>
struct function_traits;

template <typename ReturnType, typename Class, typename ...ArgumentTypes>
struct function_traits<ReturnType (Class::*)(ArgumentTypes...)>
{
    typedef ReturnType (Class::*Signature)(ArgumentTypes...);
    typedef ReturnType (*FuncPtr)(void const *ip, ArgumentTypes&& ...);

    template <Signature mf>
    static ReturnType wrapper(void const *p, ArgumentTypes&& ...args)
    {
        Class* instance = const_cast<Class*>(static_cast<Class const *>(p));
        return (instance->*mf)(std::forward<ArgumentTypes>(args)...);
    }
};

template <typename Type>
constexpr auto wrap(Type p) -> typename function_traits<Type>::FuncPtr
{
    return &(function_traits<Type>::template wrapper<p>); // ERROR: Address of overloaded function 'wrapper' does not match required type 'void (const void *)'
}

int main()
{
    auto v = wrap(&bar::baz);
}

      

I tested it with Xcode 4.5.2 - Apple clang version 4.1 (tags / Apple / clang-421.11.66) (Based on LLVM 3.1svn)
Am I too wanting ?

+3


source to share


1 answer


Parameter declaration

constexpr auto wrap(Type p)

      

incompatible with template name

template wrapper<p>

      



Even in a function, a constexpr

parameter cannot be used as a constant expression.

This error usually manifests itself in trying to adjust the return type of a function constexpr

to match the value of the argument, but this is a little more subtle because the type expression is part of the value evaluation, and the value is always of the same type.

The main problem is that the template is asked to do the work at runtime. You can decide which PTMF to call it with at runtime.

constexpr

never limits the arguments that can be passed to a function. (Ie that a function can only be called with constant arguments.) It only makes the function a candidate for use in contexts where a constant is required.

+4


source







All Articles