是否可以使用明确的模板参数调用模板的用户定义转换操作员

Is it possible to call templated user-defined conversion operator with explicit template arguments?

本文关键字:用户 定义 转换 操作员 调用 参数 是否 可以使      更新时间:2023-10-16

让我们考虑以下代码(用 clang 7.0.0 成功编译,编译器参数为 -std=c++17 -Wall -Wextra -Werror -pedantic-errors):

#include <iostream>

struct Foo
{
    template <typename Type = void>
    operator int()
    {
        return 42;
    }
};

int main()
{
    const auto i = Foo{}.operator int();
    std::cout << i << std::endl;
}

是否可以使用明确提供的模板参数调用这种模板的用户定义的转换操作员?天真的方法没有编译:

const auto i = Foo{}.operator int<bool>();

[temp.names](模板专业名称)/1:

模板专业化可以用 template-id

引用
simple-template-id:
  template-name < template-argument-listₒₚₜ >
template-id:
  simple-template-id
  operator-function-id < template-argument-listₒₚₜ >
  literal-operator-id < template-argument-listₒₚₜ >
template-name:
  identifier

如您所见,没有转换 - 函数-ID

conversion-function-id:
    operator conversion-type-id

template-id 语法中提到的。所以答案是否定的。不可能。