c++ - 模板类中的模板转换运算符 - 到函数指针
问题描述
我正试图让我的类可以转换为函数指针,原因有很多与这篇文章无关的原因。
当我尝试使用非模板类执行此操作时,它工作正常。下面,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 {};
}
解决方案
你可以试试这个:
#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
是强制使用重载的运算符成员函数。
推荐阅读
- android - 为什么我们需要有 FloatSpringSpec 既然我们已经有了 SpringSpec
可以是 SpringSpec ? - android - 如何获取 Widevine “DRM License Url” 在 ExoPlayer Android 中播放视频
- javascript - 如何禁用某个功能
- sql - 如何将 SQL 语言高亮自动注入 Intellij IDEA 中的某些 JSON 字段?
- multithreading - 我想制作 rust 的 for 语句多线程
- javascript - 检查数组数组中的所有数组数组是否为空
- typescript - 是否可以将原型属性添加到从另一个模块导入的类?
- swift - 图像未通过 POST 完整传输到服务器
- c++ - 如何在模板化函数(c++)的返回类型中保留引用?
- javascript - JS - VB.Net - CBC 加密