首页 > 解决方案 > 涉及自动参数和临时对象的模板专业化选择问题

问题描述

给定以下代码,具有自动参数的模板函数的特化......

#include <iostream>
#include <string>

template<typename T>
void f(auto val);

template<>
void f<int>(const std::string&) { std::cout << "ok\n"; }

int main() {
    f<int, const std::string&>("xxx");  // ok
    // f<int>("xxx");                   // won't compile    

    f<int, const std::string&>(std::string("xxx"));  // ok
    // f<int>(std::string("xxx"));                   // won't compile
}

为什么编译器(在这种情况下是带有 C++17 的 GCC)在没有明确指定自动参数类型的情况下不能选择专业化?

标签: c++templatesautotemporary

解决方案


推荐阅读