是否可以在调用operator()时提供模板参数?
Is it possible to supply template parameters when calling operator()?
我想使用模板operator()
,但我不确定是否可能。下面是一个无法编译的简单测试用例。是我的语法有问题,还是这根本不可能?
struct A {
template<typename T> void f() { }
template<typename T> void operator()() { }
};
int main() {
A a;
a.f<int>(); // This compiles.
a.operator()<int>(); // This compiles.
a<int>(); // This won't compile.
return 0;
}
就像chris在评论中提到的,不,不使用速记语法。必须使用完整的.operator()<T>()
语法;
如果您真的想要使用模板化的operator()
,并且想要避免编写像a.operator()<int>();
这样的结构,您可以添加一个辅助参数:
template <typename T>
struct type{};
struct A
{
template<typename T>
void operator()(type<T>) { }
};
int main()
{
A a;
a(type<int>());
}
现场演示。
在c++ 14中,你甚至可以通过变量模板省略a(type<int>());
中的空括号:
template <typename T>
struct type_{};
template <typename T>
constexpr type_<T> type{};
struct A
{
template<typename T>
void operator()(type_<T>) { }
};
int main()
{
A a;
a(type<int>);
}
现场演示。
您想要使用的确切语法在c++语言中是不可能的。
根据你想要解决的实际问题(这不在问题中),我可以想到至少三个选项:
- 使用命名函数代替操作符。
- 模板
A
而不是操作符本身。 - 使用详细拼写来调用
operator()
(我不太喜欢这个选项)。
相关文章:
- 当对话框被接受时,如何用参数调用槽
- 使用用户定义的参数调用future/async并调用类方法
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 不允许运算符 const 参数调用 const 成员函数
- 为变量模板的每个参数调用模板函数
- 如何在窗口中使用注入的 dll 中的参数调用函数
- 按引用调用与按指针参数调用的差异 前递增和后递增
- 为什么使用不匹配的参数调用重载函数仍然有效
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 基于枚举参数调用专用模板方法
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- 如何使用类模板参数来更改参数调用和函数签名?
- lambda 函数使用其参数作为模板参数调用模板函数
- Android:使用 c++ 中的 byte[] 参数调用 java 方法
- 使用不同的模板参数调用模板类的对象
- C++编译时检查是否可以用某种类型的参数调用重载函数
- 是否可以基于类模板的参数调用类方法和全局方法
- 使用单独的参数调用"boost::process::system()"时,获取"execv
- C++大括号初始值设定项作为参数调用不同的构造函数,然后预期