最終更新:2026-10-12
C++ 可変引数テンプレート¶
《C++那些事》の可変引数テンプレート¶
最近 Arrow のソースコードを読んでいて、なかなか面白い設計を見つけました。1つのplanにはproj、aggなどの複数のノードを追加できます。
今日はこの部分の設計と実装について解説します。
1.ノードの追加¶
1つのplanには通常、多数のノードを追加する必要があります。ここではEmplaceNodeを呼び出すことでそれを実現しています。
return plan->EmplaceNode<ScalarAggregateNode>(
plan, std::move(inputs), schema(std::move(fields)), std::move(target_field_ids),
std::move(aggregates), std::move(kernels), std::move(states),
std::move(owned_options));
同様に、projノードを追加する場合は次のようになります:
return plan->EmplaceNode<ProjectNode>(plan, std::move(inputs),
schema(std::move(fields)), std::move(exprs),
project_options.async_mode);
では、いったい何がこのコードをこれほどスムーズにしているのでしょうか?
ここでPlanを簡単に書いてみます:
class ARROW_EXPORT ExecPlan
{
public:
template <typename Node, typename... Args>
Node* EmplaceNode(Args&&... args) {
std::unique_ptr<Node> node{new Node{std::forward<Args>(args)...}};
auto out = node.get();
AddNode(std::move(node));
return out;
}
}
一見、この文法は非常に複雑に見えます。そう、これはC++11以降の可変引数テンプレートです。このコードの意味を説明すると、パラメータパックを対応するNodeのコンストラクタに渡す、ということです。この例は少し複雑に見えるかもしれませんので、次はDemoの時間です。
2.Demo¶
次に、2つの異なるノード(ノードAとノードB)を持つグラフを作成します。簡単にするため、ここでは関数テンプレートのEmplaceNodeを使用します。
NodeA* nodeA = EmplaceNode<NodeA>("Node A", 10, 3.14);
NodeB* nodeB = EmplaceNode<NodeB>(1, "Node B");
完全なコードは次のとおりです:
#include <iostream>
#include <vector>
#include <memory>
class NodeA {
public:
NodeA(const std::string& name, int value, double weight)
: name_(name), value_(value), weight_(weight) {}
const std::string& GetName() const {
return name_;
}
private:
std::string name_;
int value_;
double weight_;
};
class NodeB {
public:
NodeB(int id, const std::string& desc)
: id_(id), desc_(desc) {}
int GetID() const {
return id_;
}
private:
int id_;
std::string desc_;
};
template<typename Node, typename... Args>
Node* EmplaceNode(Args&&... args) {
std::unique_ptr<Node> node{new Node{std::forward<Args>(args)...}};
auto out = node.get();
// AddNode(std::move(node));
return out;
}
int main() {
NodeA* nodeA = EmplaceNode<NodeA>("Node A", 10, 3.14);
NodeB* nodeB = EmplaceNode<NodeB>(1, "Node B");
std::cout << "Node A name: " << nodeA->GetName() << std::endl;
std::cout << "Node B ID: " << nodeB->GetID() << std::endl;
return 0;
}
3.発展:任意の型のデータを出力できるprint関数を実装する¶
簡単な実装版:
可変引数テンプレート+再帰で実装するだけです。
毎回1つと残りの山に分解し、1つだけが残るまで繰り返します。したがって、1つを処理する関数と、1つ+残りの山を処理する関数の2つがあり、それぞれ最初のprint_implと2番目のprint_implに対応します。
#include <iostream>
#include <utility>
template <typename T>
void print_impl(T&& t) {
std::cout << t;
}
template <typename T, typename... Args>
void print_impl(T&& t, Args&&... args) {
std::cout << t;
print_impl(std::forward<Args>(args)...);
}
template <typename... Args>
void print(Args&&... args) {
print_impl(std::forward<Args>(args)...);
}
int main() {
int x = 1;
const char* str = "Hello, world!";
print("The value of x is ", x, ", and the string is ", str, ".\n");
return 0;
}