하지만, 청소기 IMO : 당신은 모호함 해상도를 개선하기 위해 상속을 사용하여 생성자의 템플릿 인수에 enable_if
의 이동 : 일치하는 유형의 당신은 부분적으로 전문화 할 수 있습니다.
#include <iostream>
#include <string>
#include <type_traits>
using namespace std;
template <int N>
class Disambiguator;
template<>
class Disambiguator<0>{};
template <int N>
class Disambiguator : public Disambiguator<N-1>{};
using Disambiguate = Disambiguator<100>;
template< typename type_1, typename type_2 > struct result
{
template <typename T, typename U>
using IsSame = typename enable_if<is_same<T, U>::value>::type;
template <typename T, typename U>
using IsNotSame = typename enable_if<!is_same<T, U>::value>::type;
template <typename T = type_1, typename U = type_2, typename = IsNotSame<T,U>>
result(type_1 f, Disambiguator<0>) : foo{f} {cout<<"NotSameType"<<endl;}
template <typename T = type_1, typename U = type_2, typename = IsNotSame<T,U>>
result(type_2 b, Disambiguator<1>) : bar{b} {cout<<"NotSameType"<<endl;}
// I want to enable this constructor only if type_1 == type_2
template <typename T = type_1, typename U = type_2, typename = IsSame<T,U>>
result(type_1 f, type_2 b) : foo{f}, bar{b} {cout<<"SameType"<<endl;}
// Other member functions removed.
type_1 foo;
type_2 bar;
};
int main()
{
result<float, int> c(1.0, Disambiguate{});
result<float, int> i(0, Disambiguate{});
result<int, int> j(0, 0);
result<string, int> s("abc", Disambiguate{});
result<string, int> si(0, Disambiguate{});
return 0;
}
편집 : 당신은 Xeo의 오버로드 확인 아이디어 here @ 읽을 수 있습니다. 이것이 위 코드에서 사용한 것입니다.
'result' 객체에 표시된 멤버 함수가 많아서 전문화하면 많은 코드 중복이 발생할 수 있습니다. –
@DrTwox 그런 다음 브라이언의 솔루션을 사용하십시오. 불행히도 나는 현재 어떤 대안도 모르고있다. – 0x499602D2
@DrTwox 하나의 클래스에 모든 공통 코드를 넣고 다른 클래스에 특수 코드를 넣으면 반복을 피하기 위해 상속을 사용할 수 있습니다. 이것은 일반적인 해결책입니다. 상황에 따라 CRTP를 포함한 여러 가지 방법으로이 작업을 수행 할 수 있습니다. 예를 들어, 기본 클래스에 생성자 (및 데이터 멤버)를 둘 수 있습니다.이 클래스는 두 경우 모두에 대해 같거나 비슷하지 않으며 파생 클래스에서 상속 된 생성자 (C++ 11)를 사용합니다. 또는 반대로, 파생 클래스를 기본 클래스의 모든 공통 코드와 함께 전문화하십시오. –