簡體   English   中英

constexpr函數,返回模板化函數實例的地址

[英]constexpr function that returns address of the templated function instance

請考慮以下示例:

#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);
}

我用Xcode 4.5.2測試了它 - Apple clang 4.1版(標簽/ Apple / clang-421.11.66)(基於LLVM 3.1svn)
我想要太多嗎?

參數聲明

constexpr auto wrap(Type p)

與模板名稱不兼容

template wrapper<p>

即使在constexpr函數中,參數也不能用作常量表達式。

通常這個錯誤表現為嘗試根據參數的值調整constexpr函數的返回類型,但這是一個小的微妙,因為類型表達式是值計算的一部分,值始終具有相同的類型。

根本問題是要求模板執行運行時工作。 您可以決定在運行時調用它的PTMF。

constexpr永遠不會限制可能傳遞給函數的參數。 (即,只能使用常量參數調用函數。)它僅使函數成為在需要常量的上下文中使用的函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM