C++ templateの明示的特殊化について

otaky 120 Reputation points
2023-09-07T08:53:15.7566667+00:00
template<int N> void func2(int a = N){
    cout << "Primary:" << a  << endl;
}
template<> void func2<10>(int b){
    cout << "func2<10>:" << b  << endl;
}

int main(void){
    // Your code here!
    func2<100>();
    func2<10>();
}

上記のfunc2<10>()がなぜコンパイルが成功するのか理解できません。

また引数bは10が代入されたことになります。なぜでしょうか?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,906 questions
{count} votes

Accepted answer
  1. Minxin Yu 13,501 Reputation points Microsoft External Staff
    2023-09-08T03:01:24.3433333+00:00

    Hi, @otaky

    template<int N> void func2(int a = N) provides default parameter a=N.
    template<> void func2<10>(int b) is a specialization of template<int N> void func2(int a = N).

    Declaration (and function signature) is determined by the primary template.

    Since func2<10>() has no parameter input. It uses default parameter N 10.

    Below is a simplified example:

    #include <iostream>
    using namespace std;
    
    template<int N> void func2(int a = N);
    
    template<> void func2<10>(int b) {
       
        cout << "func2<10>:" << b << endl;
    }
    
    int main(void) {
       
        func2<10>();
    }
    

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.