Con*_*tor 2 c++ templates type-conversion conversion-operator language-lawyer
让我们考虑以下代码(使用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;
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用显式提供的模板参数调用此类模板化的用户定义转换运算符?天真的方法不能编译:
const auto i = Foo{}.operator int<bool>();
Run Code Online (Sandbox Code Playgroud)
模板专业化可以通过template-id来引用:
Run Code Online (Sandbox Code Playgroud)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
如您所见,没有conversion-function-id
conversion-function-id:
operator conversion-type-id
Run Code Online (Sandbox Code Playgroud)
在template-id语法中提到。