LoginSignup
0
0

More than 5 years have passed since last update.

C++テンプレートの関数及びクラスの明示的特殊化の例

Posted at

関数の明示的特殊化
boolの時だけ挙動を変える

using namespace std;
template <typename T>
void testFunc(T arg){
    cout << arg << endl;
}

template <>
void testFunc(bool arg){
    cout << (arg ? "yes":"no") << endl;
}

int main(){
    testFunc(30);
    testFunc(false);
    return 0;
}

クラスの明示的特殊化
boolの時だけprintの挙動を変える

#include <iostream>
using namespace std;
template <typename T>
class TestClass {
    public:
    TestClass (T data):data(data){};
    void print() const{
        cout << data << endl;
    }
    protected:
    T data;
};

template <>
class TestClass<bool> {
public:
    TestClass (bool data):data(data){};
    void print() const{
        cout << (data ? "yes" : "no") << endl;;
    }
protected:
    bool data;
};

int main(){
    TestClass<int> t(30);
    t.print();

    TestClass<bool> u(true);
    u.print();
    return 0;
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0