选择涉及自动参数和临时对象的模板专业化问题

问题描述 投票:1回答:1

给出以下代码,并带有自动参数的模板函数特化...

#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
}

为什么在没有显式指定自动参数类型的情况下,编译器(在这种情况下为GCC w / C ++ 17)不能选择特殊化?

c++ templates auto temporary
1个回答
0
投票

给定f<int>("xxx");"xxx"的类型为const char[],然后将auto推导为const char*,它与专业化的参数类型const string&不匹配,因此将不被选择。

给出f<int>(std::string("xxx"));auto将被推导为std::string,它也与const string&不匹配,因此也不会选择专业化。

如果将主模板更改为

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

那么您可以

f<int, std::string>("xxx");  // ok
f<int, std::string>(std::string("xxx"));  // ok

f<int>(std::string("xxx"));

对于f<int>("xxx");,您仍然必须将其明确转换为std::string,或者尝试为其提供其他特殊化或重载。

LIVE

© www.soinside.com 2019 - 2024. All rights reserved.