LoginSignup
65
57

More than 5 years have passed since last update.

テンプレート関数の宣言と実装を分離する方法

Posted at

自分の備忘録のために投稿する。

ヘッダにはテンプレート関数の宣言のみ記述し、定義は実装ファイルに書く場合、単純にヘッダと実装を分離したのではリンクエラーが出るが、下記の様にすればリンクエラーを回避できる。
本手法はBoostでも使用されている手法であるため、悪くない手法であると思う。

Utility.h : テンプレート関数の宣言のみ記述したファイル

// Utility.h
#pragma once

#include <string>                                                                               

template<typename T>                                                                            
class Utility
{
    public:
        std::string toString(const T & value);                                                  
};

#include "details/Utility.h"

details/Utility.h : 上記ファイル ( Utility.h ) で宣言したテンプレート関数の実装を記述したファイル

// details/Utility.h
#include "../Utility.h"
#include <sstream>

template<typename T>
std::string Utility<T>::toString(const T & value)
{
    std::stringstream ss; 
    ss << value;
    return ss.str();
}

main.cpp : Utilityクラスの使用法を説明するためのファイル

// main.cpp
#include <iostream>
#include "Utility.h"

int main()
{
    Utility<int> utility;
    std::cout << utility.toString(20) << std::endl;
    return 0;
}
65
57
0

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
65
57