【问题标题】:Is it possible to call templated user-defined conversion operator with explicit template arguments?是否可以使用显式模板参数调用模板化的用户定义转换运算符?
【发布时间】:2019-08-12 01:05:21
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    [temp.names](Names of template specializations)/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
    

    如你所见,没有conversion-function-id

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

    template-id语法中提到。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-25
        • 1970-01-01
        • 2021-12-28
        相关资源
        最近更新 更多