如何使用模板函数提供的参数调用函数

How to call a function using an argument supplied from the template function

本文关键字:函数 参数 调用 何使用      更新时间:2023-10-16

编辑:只是为了澄清"t"在强制转换时被成功调用。编译器知道并声明它是一个接受int类型实参的函数指针。我提供了一个空int指针来打破循环,因为它递归地调用自己。这可能只是编译器中的一个错误。

我正在尝试从模板函数参数调用函数。我认为可以在没有显式转换的情况下调用函数,但情况似乎并非如此。使用VC2013。

template<typename T>
void func(T t)
{
    printf("calling func...n");
    if (t)
    {
        ((void(__cdecl*)(int))t)((int)nullptr);     // explicit casting is successful
        t ((int)nullptr);                           // compile error: ``term does not evaluate to a function taking 1 arguments``
    }
}
void main()
{
    auto pe = func < int > ;
    auto pf = func < void(__cdecl*)(int) >;
    pf(pe);

}

func<int>的错误变成:

void func(int t)
{
    printf("calling func...n");
    if (t)
    {
        ((void(__cdecl*)(int))t)((int)nullptr); // bad casting
        t ((int)nullptr);                       // compile error: int is not a callable object
    }
}

t是一个int时,当然你不能把它当作一个函数。您必须对int s的模板进行专门化,或者使用不同的函数。另外,请忘记还有c风格的cast,它们只会把你自己射到脚上。

我不明白你到底想要什么。但也许像这样?:

#include <iostream>
#include <type_traits>
template<typename T>
void call_helper(T value, std::true_type) // value is function
{
    std::cout << "Function" << std::endl;
    value(0);
}
template<typename T>
void call_helper(T value, std::false_type) // value is NOT function
{
    std::cout << "Not function" << std::endl;
    std::cout << value << std::endl;
}
template<typename T>
void call(T value)
{
    call_helper(value, std::is_function<typename std::remove_pointer<T>::type>());
}
int main()
{
    void (*f)(int) = call<int>;
    call(f);
}

实例:http://rextester.com/DIYYZ43213