小编Zho*_*eng的帖子

Why does this template function not behave as expected?

I was reading about template functions and got confused by this problem:

#include <iostream>

void f(int) {
    std::cout << "f(int)\n";
}

template<typename T>
void g(T val) {
    std::cout << typeid(val).name() << "  ";
    f(val);
}

void f(double) {
    std::cout << "f(double)\n";
}

template void g<double>(double);

int main() {
    f(1.0); // f(double)
    f(1);   // f(int)
    g(1.0); // d  f(int), this is surprising
    g(1);   // i  f(int)
}
Run Code Online (Sandbox Code Playgroud)

The results are the same if I don't write template void g<double>(double);.

I …

c++ dependent-name function-templates name-lookup unqualified-name

17
推荐指数
2
解决办法
570
查看次数