Skip to content

Instantly share code, notes, and snippets.

@draftcode
Created August 1, 2012 07:55
Show Gist options
  • Select an option

  • Save draftcode/3224733 to your computer and use it in GitHub Desktop.

Select an option

Save draftcode/3224733 to your computer and use it in GitHub Desktop.
Conversion FunctionとConstructor
#include <iostream>
using namespace std;
struct C;
struct D {
operator C();
};
struct C {
C() {}
C(D) {
cout << "constructor C(D)" << endl;
}
};
D::operator C() {
cout << "operator C" << endl;
return C();
}
void f(C c) {}
int main() {
D d;
// CはDのConversion Functionとコンストラクタのどちらの方法でも生成可能
f(static_cast<C>(d));
f((C) d);
f(C(d));
f(d);
// このままだと一番下の式でerror: conversion from 'D' to 'C' is ambiguousとな
// りコンパイルエラー
// コンストラクタC(D)をexplicitにすると
//
// f(static_cast<C>(d)); // constructor C(D)
// f((C) d); // constructor C(D)
// f(C(d)); // constructor C(D)
// f(d); // operator C
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment