首页 > 解决方案 > 模板类中的模板转换运算符 - 到函数指针

问题描述

我正试图让我的类可以转换为函数指针,原因有很多与这篇文章无关的原因。

当我尝试使用非模板类执行此操作时,它工作正常。下面,Bar bar; bar(1)按预期正确编译和段错误。但Foo<int>; foo(1)根本不编译。

我尝试了多个编译器,我得到:mismatched types 'Args' and 'int'

有任何想法吗?现场演示:https ://wandbox.org/permlink/alSGBssfSd4pHgdl

#include <iostream>
#include <tuple>

using namespace std;

template<typename... Args>
using Test = void(*)(Args...);

template<typename T>
struct Foo {
    template<typename... Args>
    operator Test<Args...>() {
        return Test<Args...>{};
    }
};

struct Bar {
    template<typename... Args>
    operator Test<Args...>() {
        return Test<Args...>{};
    }
};

int main()
{
    Foo<int> foo;
    // foo(1);
    
    Bar bar;
    bar(1);
    
    return 0;
}

也尝试了这种糟糕的语法:

    template<typename... Args>
    (*operator void() const)(Args...) {
      return {};
    }

标签: c++templatestype-conversionfunction-pointersimplicit-conversion

解决方案


你可以试试这个:

#include <iostream>
#include <tuple>

using namespace std;

template<typename... Args>
using Test = void(*)(Args...);

template<typename T>
struct Foo {
    template<typename... Args>
    operator Test<Args...>()
    {
        std::cout << __FUNCTION__ << std::endl;
        return Test<Args...>{};
    }
};

struct Bar {
    template<typename... Args>
    operator Test<Args...>()
    {
        std::cout << __FUNCTION__ << std::endl;
        return Test<Args...>{};
    }
};

int main()
{
    Foo<int> foo;
    auto x = static_cast<Test<int, double>>(foo);

    Bar bar;
    auto y = static_cast<Test<char, float>>(bar);

    return 0;
}

使用 Visual C++ 2019 时,我得到以下运行时输出:

Foo<int>::operator void (__cdecl *)(int,double)
Bar::operator void (__cdecl *)(char,float)

的使用static_cast是强制使用重载的运算符成员函数。


推荐阅读