是否可以在调用operator()时提供模板参数?

Is it possible to supply template parameters when calling operator()?

本文关键字:参数 调用 operator 是否      更新时间:2023-10-16

我想使用模板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()(我不太喜欢这个选项)。