可以使用显式模板参数调用模板化的用户定义转换运算符吗?

时间:2019-03-21 08:02:46

标签: c++ templates type-conversion language-lawyer conversion-operator

让我们考虑以下代码(使用 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>();

2 个答案:

答案 0 :(得分:4)

[temp.names](Names of template specializations)/1

  

模板专业化可以通过 template-id 来引用:

tracker

如您所见,没有 conversion-function-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
template-id 语法中提到的

答案 1 :(得分:0)

我知道这个问题是针对高级场景的,正在询问代码是否符合标准,但让我们在这里退一步:

运算符转换旨在定义“类似静态广播”的操作。静态转换依赖于另一个模板类型并没有什么意义