简体   繁体   中英

Can internal linkage rule break a valid c++03 code in c++11?

If there is valid code in c++03, Can it break in c++11 because of Internal linkage rule introduced?

Clause C.2.6 Clause 14: templates point 3 14.6.4.2

I am not able to think of any example.

Any help is appreciated.

For reference, this is the C++03 version of §14.6.4.2 [temp.dep.candidate] "Candidate functions":

For a function call that depends on a template parameter, if the function name is an unqualified-id but not a template-id , the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that:

  • For the part of the lookup using unqualified name lookup (3.4.1), only function declarations with external linkage from the template definition context are found.
  • For the part of the lookup using associated namespaces (3.4.2), only function definitions with external linkage found in either the template definition context or the template instantiation context are found.

If the call would be ill-formed or would find a better match had the lookup within the associated namespaces considered all the function declarations with external linkage introduced in those namespaces in all translation units, not just considering those declarations found in the template definition and template instantiation contexts, then the program has undefined behaviour.

You can make some example code that would be well defined in C++03, but not C++11:

#include <iostream>

void print(short x) {
    std::cout << x;
}

static void print(long x) {
    std::cout << x;
}

template<typename T>
void print_twice(T x) {
    print(x);
    print(x);
}

int main() {
    print_twice(0);
    // C++03: `void print(long)` does not have external linkage so is not considered.
    //        Calls `void print(short)` twice
    
    // C++11: Both `void print(long)` and `void print(short)` are viable,
    //        but neither is better so it is ambiguous (compile time error)
}

(Though clang and gcc don't seem to implement the C++03 version of ADL, so this would never come up when compiling with those compilers at least)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM